Skip to content

[Edit] PHP: Arrays #7207

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
288 changes: 259 additions & 29 deletions content/php/concepts/arrays/arrays.md
Original file line number Diff line number Diff line change
@@ -1,59 +1,289 @@
---
Title: 'Arrays'
Description: 'In PHP, an array is an ordered map that can hold more than one value.'
Description: 'In PHP, an array is a special variable that can hold more than one value at a time.'
Subjects:
- 'Web Development'
- 'Computer Science'
- 'Web Development'
Tags:
- 'Arrays'
- 'Data Types'
- 'Functions'
- 'Values'
CatalogContent:
- 'learn-php'
- 'paths/front-end-engineer-career-path'
- 'paths/computer-science'
---

An array can hold more than one value. In PHP, they're stored as value pairs that in other languages would be called a dictionary or a hashtable. Keys can be strings or integers.
In PHP, an **array** is a special variable that can hold more than one value at a time. Rather than creating multiple variables to store related data, arrays group data logically under one variable name. PHP supports three main types of arrays:

- **Indexed Arrays**: Arrays having a numeric index.
- **Associative Arrays**: Arrays having named keys.
- **Multidimensional Arrays**: Arrays having one or more arrays in it.

## Creating Arrays

There are different ways to create an array in PHP. Let's check them out one-by-one.

### Indexed Arrays

The `array()` function is used to create an indexed array:

```php
$colors = array("Red", "Green", "Blue");
```

Here is a shorter syntax that can also be used to create an indexed array:

```php
$colors = ["Red", "Green", "Blue"];
```

### Associative Arrays

An associative array can be created like this:

```php
$person = [
"name" => "John",
"age" => 30,
"email" => "[email protected]"
];
```

### Multidimensional Arrays

A multidimensional array can be created like this:

```php
$users = [
["name" => "Alice", "age" => 25],
["name" => "Bob", "age" => 28]
];
```

## Accessing Arrays

There are different ways to access an array in PHP. Let's check them out one-by-one.

### Indexed Arrays

This example accesses the first item in the indexed array `colors`:

## Syntax
```php
<?php
$colors = ["Red", "Green", "Blue"];

echo $colors[0]; // Output: Red
?>
```

### Associative Arrays

This example accesses the value associated with the `"name"` key in the associative array `person`:

```php
<?php
$person = [
"name" => "John",
"age" => 30
];

echo $person["name"]; // Output: John
?>
```

### Multidimensional Arrays

There are several methods of declaring an array in PHP. The `array()` function can be used, either with key-value pairs, or with values alone. Single brackets, `[...]` can also be used in place of the `array()` keyword. If any key value is omitted, the key will be found by incrementing the largest prior integer key. If a key is repeated, the new value will overwrite the prior key.
This example accesses the value associated with the `"name"` key for the second user in the multidimensional array `users`:

```php
<?php
// The last comma can be omitted
$array1 = array( "item 1" => "one", "item 2" => "two", "item 3" => "three", );
$users = [
["name" => "Alice", "age" => 25],
["name" => "Bob", "age" => 28]
];

echo $array1["item 1"], ";", $array1["item 2"], ";", $array1["item 3"];
// Output: one;two;three
echo $users[1]["name"]; // Output: Bob
?>
```

$array2 = array("one", "two", "three");
## Updating Arrays

echo $array2[0], ";", $array2[1], ";", $array2[2];
// Output: one;two;three
This example updates the second item of the indexed array `colors` and the value associated with the key `"age"` in the associative array `person`:

$array3 = ["one", 5 => "two", "three"];
```php
<?php
$colors = ["Red", "Green", "Blue"];

echo $array3[0], ";", $array3[5], ";", $array3[6];
// Output: one;two;three
$colors[1] = "Yellow";

$array4 = [5 => "one", 5.7 => "two", "5" => "three"];
$person = [
"name" => "John",
"age" => 30
];

echo $array4[5];
// Output: three
$person["age"] = 31;

print_r($colors[1]);
print_r("\n");
print_r($person["age"]);
?>
```

When defining an array, the following key casts will occur:
Here is the output:

```shell
Yellow
31
```

## Adding Items to an Array

This example adds a new item to the indexed array `colors` and a new key-value pair to the associative array `person`:

- Strings containing valid `int` types, unless preceded by a `+` sign, will be cast to an `int` type key.
As in the above example `"5"` is treated as `5`.
- `float` types will be cast to `int` types, truncating the fractional part.
As in the above example `5.7` is treated as `5`.
- `bool` types are cast to `int` types. `true` is stored as `1` and `false` stored as `0`.
- `null` will be cast as the empty string, `""`.
- Arrays and objects cannot be used as keys and will result in an error: `Illegal offset type`.
```php
<?php
$colors = ["Red", "Green"];

## Array Functions
$colors[] = "Purple";

Below is a list of selected array functions:
$person = [
"name" => "John",
"age" => 30
];

$person["city"] = "New York";

print_r($colors);
print_r("\n");
print_r($person);
?>
```

Here is the output:

```shell
Array
(
[0] => Red
[1] => Green
[2] => Purple
)

Array
(
[name] => John
[age] => 30
[city] => New York
)
```

## Removing Items from an Array

This codebyte example uses the `unset()` function to remove an item from the indexed array `colors` and a key-value pair from the associative array `person`:

```codebyte/php
<?php
$colors = ["Red", "Green", "Blue"];

unset($colors[2]);

$person = [
"name" => "John",
"email" => "[email protected]"
];

unset($person["email"]);

print_r($colors);
print_r("\n");
print_r($person);
?>
```

## Frequently Asked Questions

### 1. How do I check if a value exists in an array?

Using `in_array()` and `array_key_exists()`:

```php
<?php
$colors = ["Red", "Green", "Blue"];
$person = ["name" => "Alice", "age" => 25];

if (in_array("Red", $colors)) {
echo "Red is in the array.\n";
}

if (array_key_exists("name", $person)) {
echo "The 'name' key exists.\n";
}
?>
```

Here is the output:

```shell
Red is in the array.
The 'name' key exists.
```

### 2. How can I loop through an array in PHP?

Using `foreach` to loop through indexed and associative arrays:

```php
<?php
$colors = ["Red", "Green", "Blue"];

foreach ($colors as $color) {
echo $color . "\n";
}

$person = ["name" => "Alice", "age" => 25];

foreach ($person as $key => $value) {
echo "$key: $value\n";
}
?>
```

Here is the output:

```shell
Red
Green
Blue
name: Alice
age: 25
```

### 3. How do I count the number of elements in an array?

You can use the built-in `count()` function to determine how many elements an array contains:

```php
<?php
$colors = ["Red", "Green", "Blue"];

echo "Total colors: " . count($colors);

print_r("\n");

$person = [
"name" => "John",
"age" => 30,
"email" => "[email protected]"
];

echo "Total fields: " . count($person);
?>
```

Here is the output:

```shell
Total colors: 3
Total fields: 3
```