PHP Arrays

PHP Array is a list of multiple values with different data types.

I. Create an array in PHP

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)

II. Access element in an array

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

III. Check if an array key exists

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
)
*/

V. Add an element to an array

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
)
*/

VI. Get array length

To get a length of an array, we can use the function count();

$languages = ["English", "German", "Spanish"];
echo count($languages); // 3

VII. Loop through an array

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>";
}
?>

VIII. Associative arrays

When you have names and keys in an array, it’s called an associative array.

1. Define 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
) */

2. Add an item to the array

$newLang = "Spanish";
$langScore[$newLang] = 10;

echo "<pre>";
print_r($langScore);
echo "</pre>";
/* Array
(
    [English] => 8
    [German] => 9
    [Spanish] => 10
) */

3. Loop through an associative array

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

IX. Multidimensional array

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

X. Array functions

There are different array functions in PHP. Here are some popular ones.

1. Remove an element from the beginning

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
) */

2. Remove the last element.

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
)
*/

3. Remove elements by keys

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
)
*/

4. Split the array into chunks

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
        )
)
*/

5. Combine arrays

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
) */

6. Filter an array

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_FILTER_USE_KEY - pass key as the only argument (instead of the value).
  • ARRAY_FILTER_USE_BOTH - pass both value and key as arguments (instead of the value).
$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
) */

7. Iterate over array elements

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
) */

8. Merge arrays

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
) */

9. Reduce an array to a value

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

10. Search for a value

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)

11. Find the differences between arrays

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 )

11. Sort an array

We can use the following functions to sort an array.

  • sort($ar) - Sorts the array values (loses key).
  • ksort($ar) - Sorts the array by key.
  • asort($ar) - Sorts array by value, keeping key association.
  • usort($ar) - Sort based on a callback function.
  • shuffle($ar) - Shuffles the array into a random order.

12. Array destructuring

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