diff --git a/content/php/concepts/arrays/arrays.md b/content/php/concepts/arrays/arrays.md index f2718a434ef..d7c7adda871 100644 --- a/content/php/concepts/arrays/arrays.md +++ b/content/php/concepts/arrays/arrays.md @@ -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" => "john@example.com" +]; +``` + +### 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 + +``` + +### Associative Arrays + +This example accesses the value associated with the `"name"` key in the associative array `person`: + +```php + "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 "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 + "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 + "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 + "John", + "email" => "john@example.com" +]; + +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 + "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 + "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 + "John", + "age" => 30, + "email" => "john@example.com" +]; + +echo "Total fields: " . count($person); +?> +``` + +Here is the output: + +```shell +Total colors: 3 +Total fields: 3 +```