PHP Array is a list of multiple values with different data types.
In PHP, we define an array using a square bracket [] or an array() function.
The elements of an array can have different data types, such as string, integer, and objects.
$languages = ["English", "German", "Spanish"];
$lang = array("English", "German", "Spanish");
We can use is_array($ar)
to check if a variable is an array.
$languages = ["English", "German", "Spanish"];
var_dump(is_array($languages)); // bool(true)
Similar to a string, an array is indexed by a number starting at 0.
$languages = ["English", "German", "Spanish"];
echo $languages[1]; // German
If we don’t define a key in an array, PHP automatically assigns a key as a numeric value starting at 0.
Therefore, if we try to access [-1], we will get an error.
$languages = ["English", "German", "Spanish"];
echo $languages[-1]; // Undefined array key
We can use the function isset()
or array_key_exists()
to check if an array key exists.
The difference is that isset()
also tells you if the key exists and it’s not null.
$array = ["a" => 1, "b" => null];
var_dump(isset($array["a"])); // bool(true)
var_dump(isset($array["b"])); // bool(false)
var_dump(array_key_exists("a", $array)); // bool(true)
var_dump(array_key_exists("b", $array)); // bool(true)
## IV. Update an array
We can mutate an array and update the value at a specific index using a square bracket [].
```php
$languages = ["English", "German", "Spanish"];
$languages[2] = "Korean";
echo "<pre>";
print_r($languages);
echo "</pre>";
/* Output:
Array
(
[0] => English
[1] => German
[2] => Korean
)
*/
We can add a new element to an array by using a square bracket [] or the array_push()
function.
$languages = ["English", "German", "Spanish"];
$languages[] = "Italian";
echo "<pre>";
print_r($languages);
echo "</pre>";
/* Output:
Array
(
[0] => English
[1] => German
[2] => Spanish
[3] => Italian
)
*/
To get a length of an array, we can use the function count()
;
$languages = ["English", "German", "Spanish"];
echo count($languages); // 3
We can use For loop to loop through an array:
<?php
$colors = ["Red", "Blue", "Green"];
$arrLength = count($colors);
for($x = 0; $x < $arrLength; $x++) {
echo $colors[$x];
echo "<br>";
}
?>
When you have names and keys in an array, it’s called an associative array.
You can define and name your key by using the structure key => value
.
$langScore = [
"English" => 8,
"German" => 9
];
echo "<pre>";
print_r($langScore);
echo "</pre>";
/* Array
(
[English] => 8
[German] => 9
)
*/
Note: If an array has the same key, the last one will overwrite the others.
$array = [0 => "Hey", 1 => "Yes", 1 => "No"];
echo "<pre>";
print_r($array);
echo "</pre>";
/* Array
(
[0] => Hey
[1] => No
) */
$newLang = "Spanish";
$langScore[$newLang] = 10;
echo "<pre>";
print_r($langScore);
echo "</pre>";
/* Array
(
[English] => 8
[German] => 9
[Spanish] => 10
) */
To loop through and print all the values of an associative array, you could use a foreach loop, like this:
$langScore = [
"English" => 8,
"German" => 9
];
foreach($langScore as $k => $v ) {
echo "Key=".$k." Val=".$v.'<br>';
}
// Key=English Val=8
// Key=German Val=9
A multidimensional array is an array containing one or more arrays.
$products = [
'paper' => [
'copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper"
],
'pens' => [
'ball' => "Ball Point",
'hilite' => "Highlighters",
'marker' => "Markers"
],
'misc' => [
'tape' => "Sticky Tape",
'glue' => "Adhesives",
'clips' => "Paperclips"
]
];
echo $products["pens"]["marker"];
// Markers
There are different array functions in PHP. Here are some popular ones.
We can remove an element from an array’s beginning using the array_shift()
function.
$array = [15, 9, 3, 5, 1];
echo array_shift($array); // 15
echo "<pre>";
print_r($array);
echo "</pre>";
/*
Array
(
[0] => 9
[1] => 3
[2] => 5
[3] => 1
) */
We can remove an element from an array’s end using the array_pop()
function.
$array = [15, 9, 3, 5, 1];
echo array_pop($array); // 1
echo "<pre>";
print_r($array);
echo "</pre>";
/*
Array
(
[0] => 15
[1] => 9
[2] => 3
[3] => 5
)
*/
We can also remove elements from an array by specifying keys with unset()
.
We’ll need to specify the key. Otherwise, the whole array is destroyed.
$array = [15, 9, 3, 5, 1];
unset($array[3]);
echo "<pre>";
print_r($array);
echo "</pre>";
/*
Array
(
[0] => 15
[1] => 9
[2] => 3
[4] => 1
)
*/
We can use array_chunk() to split an array into chunks of new arrays.
array_chunk(array, length, preserve_key)
$items = ["a" => 0, "b" => 1, "c" => 2, "d" => 3, "e" => 4, "f" => 5];
echo "<pre>";
print_r(array_chunk($items,2, true));
echo "</pre>";
/* Array
(
[0] => Array
(
[a] => 0
[b] => 1
)
[1] => Array
(
[c] => 2
[d] => 3
)
[2] => Array
(
[e] => 4
[f] => 5
)
)
*/
We create an array by using the values from one array as keys and another as the corresponding values.
If the size doesn’t match, the function array_combine() will throw an error.
array_combine(keys, values)
$a1 = ["a", "b"];
$a2 = [1, 2];
echo "<pre>";
print_r(array_combine($a1, $a2));
echo "</pre>";
/* Array
(
[a] => 1
[b] => 2
) */
We use array_filter() to filter the values of an array using a callback function.
array_filter(array, function, flag)
The flag is optional and it specifies what arguments are sent to the callback:
$array = [1, 2, 3, 4, 5, 6];
$even = array_filter($array, fn($num) => $num % 2 === 0);
echo "<pre>";
print_r($even);
echo "</pre>";
/* Array
(
[1] => 2
[3] => 4
[5] => 6
) */
We can iterate over an array using the array_map() function.
array_map(function, array1, array2, ...)
$array = [1, 2, 3, 4, 5, 6];
$array = array_map(fn($num) => $num * 2, $array);
echo "<pre>";
print_r($array);
echo "</pre>";
/* Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
[4] => 10
[5] => 12
) */
We can merge multiple arrays using the array_merge() function.
If arrays have the same numeric keys, it will not override the values; instead, it appends them.
However, if the arrays have the same string keys, the last one overrides the previous ones.
array_merge(array1, array2, array3, ...)
$array1 = [1, 2];
$array2 = [3, 4];
$array3 = [5, 6];
$merge = array_merge($array1, $array2, $array3);
echo "<pre>";
print_r($merge);
echo "</pre>";
/* Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
) */
array_reduce() function reduces an array to a single value using a callback function.
array_reduce(array, function, initialValue)
$items = [
["name" => "item 1", "price" => 40, "qty" => 6],
["name" => "item 2", "price" => 25, "qty" => 4],
["name" => "item 3", "price" => 30, "qty" => 5],
];
$total = array_reduce(
$items,
fn($sum, $item) => $sum + $item["qty"] * $item["price"]
);
echo $total; // 490
We can search an array using array_search()
. It will return the key of the first matching value.
The third argument indicates if we want to do a strict comparison or not. It is defaulted as false.
array_search(value, array, strict)
$a = ["a", "b", "c", "d", "b", "e"];
$key = array_search("b", $a, true);
var_dump($key); // int(1)
We can use array_diff() to find the differences between arrays.
It compares the array values and returns the differences:
array_diff(array1, array2, array3, ...)
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"black","g"=>"purple");
$a3=array("a"=>"red","b"=>"black","h"=>"yellow");
$result=array_diff($a1,$a2,$a3);
print_r($result); // Array ( [b] => green [c] => blue )
We can use the following functions to sort an array.
We can use the function list() or a square bracket to destructor an array.
$array = [1, 2, 3, 4];
[$a, $b, $c, $d] = $array;
echo "$a, $b, $c, $d"; // 1, 2, 3, 4