Skip to main content

PHP Arrays

By SamK
0
0 recommends
Topic(s)

An array is a variable that allows you to store multiple values under a single name. You can access these values by referencing their index number or name within the array.

For example, $fruit is an array, which has multiple values Apple, Banana, and Orange.

<?php
$fruits = ["Apple", "Banana", "Orange"];
?>

PHP Array Types

In PHP, arrays are categorized into three types:

  • Indexed arrays: Arrays where each element is assigned a numeric index.
  • Associative arrays: Arrays where each element is associated with a named key.
  • Multidimensional arrays: Arrays that contain one or more arrays as elements.

Array Items

Array items can be of any data type.

The most common are strings and numbers (int, float), but array items can also be objects, functions or even arrays.

You can have different data types in the same array.

Example: The below array $myArr contains three items, each having a different data type: string, integer and an array.

<?php
$myArr = ["Fruit", 25, ["oranges", "grapes"]];
?>

Array Functions

PHP offers many built-in array functions.

For example, the count() function, which counts the number of items in an array, and is mainly helpful in applying for loops to dynamic arrays where the number of items in an array are not known.

Example: $fruits is an array, which is generated dynamically and the number of items are not known.

<?php
for ($x = 0; $x < count($fruits); $x++) {
  echo "$fruits[$x] <br>";
}
?>

/*
If $fruit = array("Orange", "Apple", "Melon");
The output will be:
Orange
Apple
Melon
*/

PHP Indexed Arrays

In indexed arrays, each element is assigned a unique index number. 

By default, the first element is assigned an index of 0, the second element is assigned an index of 1, and so on.

Example: Create an indexed array and display its elements along with their corresponding index numbers.

<?php
$fruits = array("apple", "orange", "banana");
var_dump($fruits);
?>

/*
Output:
array(3) { [0]=> string(5) "apple" [1]=> string(6) "orange" [2]=> string(6) "banana" } 
*/

Access Indexed Arrays

You can access an array element by referring to its index number.

Example: Show the second element of the array.

<?php
$fruits = array("Orange", "Banana", "Apple");
echo $fruits[1];
?>

/*
Output:
Banana
*/

If you add a new item to an array, it will receive the next index number, which will be one higher than the highest existing index.

Example:

<?php
$fruits[1] = "Apple";
$fruits[2] = "Banana";

array_push($fruits, "Orange"); //adding a new item to array
var_dump($fruits);
?>

/*
Output:
array(3) { [1]=> string(5) "Apple" [2]=> string(6) "Banana" [3]=> string(6) "Orange" }
*/

Change Value

Use the index number to modify the value of an array element.

Example: Update the value of the second element.

<?php
$fruits = array("Apple", "Banana", "Orange");
$fruits[1] = "apple";
var_dump($fruits);
?>

/*
Output:
array(3) { [0]=> string(5) "Apple" [1]=> string(5) "Apple" [2]=> string(6) "Orange" }
*/

Loop Through an Indexed Array

To iterate over and print all the values in an indexed array, you can use a foreach loop, as shown below.

Example: Show all the elements of the array.

<?php
$fruits = array("Apple", "Banana", "Orange");
foreach ($fruits as $x) {
  echo "$x <br>";
}
?>

/*
Output:
Apple
Banana
Orange
*/

PHP Associative Arrays

Associative arrays are arrays where each element is associated with a specific named key that you assign in the format:

key => value

Example:

<?php
$fruits = array("name" => "Apple", "color" => "Red", "season" => "Fall");
var_dump($fruits);
?>

/*
Output:
array(3) {
  ["name"]=>
  string(5) "Apple"
  ["color"]=>
  string(3) "Red"
  ["season"]=>
  string(4) "Fall"
} 
*/

Access Associative Arrays

You can access an associated array item by referring to its key name.

Example: Show the name of the fruit.

<?php
$fruits = array("name" => "Apple", "color" => "Red", "season" => "Fall");
echo $fruits["name"];
?>

/*
Output:
Apple
*/

Change Value

To change the value of an associated array item, use the key name:

Example: Change the season item:

<?php
$fruits = array("name" => "Mango", "color" => "Yellow", "season" => "Fall");
$fruits["season"] = "Summer";
var_dump($fruits);
?>

/*
Output:
array(3) {
  ["name"]=>
  string(5) "Mango"
  ["color"]=>
  string(6) "Yellow"
  ["season"]=>
  string(6) "Summer"
} 
*/

Loop Through an Associative Array

To iterate through and print all the values stored in an associative array, you can utilize a foreach loop, as demonstrated below.

Example: Show all elements of the array, including their keys and values.

<?php
$fruits = array("name" => "Apple", "color" => "Red", "season" => "Fall");

foreach ($fruits as $key => $value) {
  echo "$key: $value <br>";
}
?>

/*
Output:
name: Apple 
color: Red 
season: Fall
*/

Creating an Array

You can create an array by using the array() function:

<?php
$fruits = array("Apple", "Banana", "Orange");
?>

You can also use a more concise syntax by using square brackets [].

<?php
$fruits = ["Apple", "Banana", "Orange"];
?>

When creating indexed arrays, keys are assigned automatically, starting at 0 and incremented by 1 for each item. Thus, the array above could also be created using keys.

<?php
$fruits = [
  0 => "Apple",
  1 => "Banana",
  2 => "Orange"
];
?>

As you can observe, indexed arrays are similar to associative arrays, except that associative arrays use names (or strings) instead of numbers as keys.

<?php
$fruits = [
  "name" => "Apple",
  "color" => "Red",
  "season" => "Fall"
];
?>

Declare an Empty Array

You can initialize an empty array first and then add items to it later.

<?php
$fruits = [];
$fruits[0] = "Apple";
$fruits[1] = "Banana";
$fruits[2] = "Orange";
?>

The same applies to associative arrays: you can declare the array first and then add items to it.

<?php
$fruits = [];
$fruits["name"] = "Apple";
$fruits["color"] = "Red";
$fruits["season"] = "Fall";
var_dump($fruits);
?>

/*
Output:
 array(3) { ["name"]=> string(5) "Apple" ["color"]=> string(3) "Red" ["season"]=> string(4) "Fall" }
*/

Mixing Array Keys

Arrays can include both indexed and named keys.

<?php
$fruits = [];
$fruits[0] = "Apples";
$fruits[1] = "Bananas";
$fruits["fruit"] = "Cherries";
var_dump($fruits);
?>

/*
Output:
 array(3) { [0]=> string(6) "Apples" [1]=> string(7) "Bananas" ["fruit"]=> string(8) "Cherries" } 
*/

Double or Single Quotes

You can use either double or single quotes when accessing an array.

<?php
$fruits = array("name" => "Apple", "color" => "Red", "season" => "Fall");

echo $fruits["name"];  // Using double quotes
echo $fruits['name'];  // Using single quotes
?>

/*
Output:
AppleApple 
*/

Execute a Function Item

Array items can be of any data type, including functions.

To execute such a function, use the index number followed by parentheses ().

Example: Invoke a function item.

<?php
function fruitFunction() {
  echo "Fruit function output";
}

$fruits = array("Apple", 15, "fruitFunction");

$fruits[2]();  // Calls the fruitFunction
?>

/*
Output:
Fruit function output
*/

Use the key name when the function is an item in an associative array.

Example: Invoke a function by referencing its key name.

<?php
function fruitFunction() {
  echo "Fruit function output.";
}

$fruits = array("favorite" => "Apple", "quantity" => 15, "message" => "fruitFunction");

$fruits["message"]();  // Calls the fruitFunction
?>

/*
Output:
Fruit function output.
*/

Update Array Items in a Foreach Loop

Use the & character in the assignment to assign the item value by reference.

This ensures that any modifications made to the array item within the loop affect the original array.

Example: Update all item values to "Grapes".

<?php
$fruits = array("Apple", "Banana", "Orange");
foreach ($fruits as &$fruit) {
  $fruit = "Grapes";  // Update each fruit to "Grapes"
}
unset($fruit);  // Unset the reference to avoid unexpected behavior
var_dump($fruits);
?>

/*
Output:
array(3) {
  [0]=>
  string(6) "Grapes"
  [1]=>
  string(6) "Grapes"
  [2]=>
  string(6) "Grapes"
}
*/

Note: Remember to use the unset() function after the loop. If you omit the unset($x) function, the $x variable will still reference the last array item.

PHP Add Array Items

To append items to an existing array, you can use the bracket [] syntax.

Example: Append one more item to the fruits array.

<?php
$fruits = array("Apple", "Banana", "Cherry");
$fruits[] = "Orange";  // Adding "Orange" to the array
var_dump($fruits);
?>

/*
Output:
array(4) { [0]=> string(5) "Apple" [1]=> string(6) "Banana" [2]=> string(6) "Cherry" [3]=> string(6) "Orange" }
*/

Associative Arrays

To add items to an associative array, use brackets [] for the key and assign a value with the = operator.

Example: Add an item to the fruits array.

<?php
$fruits = array("name" => "Apple", "color" => "Red");
$fruits["season"] = "Fall";  // Adding a new attribute
var_dump($fruits);
?>

/*
Output:
 array(3) { ["name"]=> string(5) "Apple" ["color"]=> string(3) "Red" ["season"]=> string(4) "Fall" }
*/

Add Multiple Array Items

To add multiple items to an existing array, use the array_push() function.

Example: Add three items to the fruits array.

<?php
$fruits = array("Apple", "Banana", "Cherry");
array_push($fruits, "Orange", "Kiwi", "Lemon");  // Adding multiple fruits to the array
var_dump($fruits);
?>

/*
Output:
array(6) { [0]=> string(5) "Apple" [1]=> string(6) "Banana" [2]=> string(6) "Cherry" [3]=> string(6) "Orange" [4]=> string(4) "Kiwi" [5]=> string(5) "Lemon" }
*/

Add Multiple Items to Associative Arrays

To append multiple items to an existing array, you can use the += operator.

Example: Add two items to the fruits array.

<?php
$fruits = array("name" => "Apple", "color" => "Red");
$fruits += ["season" => "Fall", "taste" => "Sweet"];  // Adding new attributes
var_dump($fruits);
?>

/*
Output:
array(4) { ["name"]=> string(5) "Apple" ["color"]=> string(3) "Red" ["season"]=> string(4) "Fall" ["taste"]=> string(5) "Sweet" }
*/

PHP Delete Array Items

To remove an item from an array, use the array_splice() function, by specifying the index and the number of items you want to delete.

Example: Remove the second item using the array_splice() function.

<?php
$fruits = array("Apple", "Banana", "Cherry");
array_splice($fruits, 1, 1);  // Removes "Banana"
var_dump($fruits);
?>

/*
Output:
  array(2) { [0]=> string(5) "Apple" [1]=> string(6) "Cherry" }
*/

To remove multiple items: 

<?php
$fruits = array("Apple", "Banana", "Cherry");
array_splice($fruits, 1, 2);  // Removes "Banana" and "Cherry"
var_dump($fruits);
?>

/*
Output:
array(1) { [0]=> string(5) "Apple" }
*/

After the deletion, the array is automatically re-indexed, starting from index 0.

Using the unset() Function:

You can also use the unset() function to remove existing items from an array.

Note: The unset() function does not re-index the array. This means that after deletion, the array will have missing indexes.

Example: Remove the second element.

<?php
$fruits = array("Apple", "Banana", "Cherry");
unset($fruits[1]);  // Removes "Banana"
var_dump($fruits);
?>

/*
Output:
array(2) {
  [0]=>
  string(5) "Apple"
  [2]=>
  string(6) "Cherry"
}
*/

To remove multiple items:

<?php
$fruits = array("Apple", "Banana", "Cherry");
unset($fruits[1], $fruits[2]);  // Removes "Banana" and "Cherry"
var_dump($fruits);
?>

/*
Output:
array(1) {
  [0]=>
  string(5) "Apple"
}
*/

Remove Item From an Associative Array

To remove items from an associative array, use the unset() function and specify the key of the item you want to delete.

Example:

<?php
$fruits = array("name" => "Apple", "color" => "Red", "season" => "Fall");
unset($fruits["color"]);  // Removes the "color" attribute
var_dump($fruits);
?>

/*
Output:
array(2) {
  ["name"]=>
  string(5) "Apple"
  ["season"]=>
  string(4) "Fall"
}
*/

Using the array_diff Function

You can also use the array_diff() function to remove specific items from an associative array.

This function returns a new array excluding the specified items.

Example: Create a new array excluding "Red" and "Fall".

<?php
$fruits = array("name" => "Apple", "color" => "Red", "season" => "Fall");
$newArray = array_diff($fruits, ["Red", "Fall"]);
var_dump($fruits);
?>

/*
Output:
array(3) {
  ["name"]=>
  string(5) "Apple"
  ["color"]=>
  string(3) "Red"
  ["season"]=>
  string(4) "Fall"
}
*/

Note: The array_diff() function compares values as parameters, not keys.

Remove the Last Item

The array_pop() function removes the last element from an array.

Example:

<?php
$fruits = array("Apple", "Banana", "Cherry");
array_pop($fruits);  // Removes "Cherry"
var_dump($fruits);
?>

/*
Output:
array(2) {
  [0]=>
  string(5) "Apple"
  [1]=>
  string(6) "Banana"
}
*/

Remove the First Item

The array_shift() function removes the first element of an array.

Example:

<?php
$fruits = array("Apple", "Banana", "Cherry");
array_shift($fruits);  // Removes "Apple"
var_dump($fruits);
?>

/*
Output:
array(2) {
  [0]=>
  string(6) "Banana"
  [1]=>
  string(6) "Cherry"
}
*/

PHP Sorting Arrays

The elements in an array can be sorted in alphabetical or numerical order, either ascending or descending, by using the below functions.

  • sort() - sorts arrays in ascending order
  • rsort() - sorts arrays in descending order
  • asort() - sorts associative arrays in ascending order by value
  • ksort() - sorts associative arrays in ascending order by key
  • arsort() - sorts associative arrays in descending order by value
  • krsort() - sorts associative arrays in descending order by key

sort()

<?php
$fruits = array("Banana", "Apple", "Cherry");
sort($fruits);  // Sorts the fruits in alphabetical order

$figures = array(4, 6, 2, 22, 11);
sort($figures);  // Sorts the fruits numerically
var_dump($fruits);
?>

/*
Output:
array(3) {
  [0]=>
  string(5) "Apple"
  [1]=>
  string(6) "Banana"
  [2]=>
  string(6) "Cherry"
}
*/

rsort()

<?php
$fruits = array("Banana", "Apple", "Cherry");
rsort($fruits);  // Sorts the fruits in reverse alphabetical order

$figures = array(4, 6, 2, 22, 11);
rsort($figures);  // Sorts the fruits numerically in reverse order
var_dump($fruits);
?>

/*
Output:
array(3) {
  [0]=>
  string(6) "Cherry"
  [1]=>
  string(6) "Banana"
  [2]=>
  string(5) "Apple"
}
*/

asort()

<?php
$fruits = array("Apple" => "4", "Banana" => "2", "Cherry" => "6");
asort($fruits);  // Sorts the fruits by their values
var_dump($fruits);
?>

/*
Output:
array(3) {
  ["Banana"]=>
  string(1) "2"
  ["Apple"]=>
  string(1) "4"
  ["Cherry"]=>
  string(1) "6"
}
*/

ksort()

<?php
$fruits = array("Apple" => "4", "Banana" => "2", "Cherry" => "6");
ksort($fruits);  // Sorts the fruits by their keys
var_dump($fruits);
?>

/*
Output:
array(3) {
  ["Apple"]=>
  string(1) "4"
  ["Banana"]=>
  string(1) "2"
  ["Cherry"]=>
  string(1) "6"
}
*/

arsort()

<?php
$fruits = array("Apple" => "4", "Banana" => "2", "Cherry" => "6");
arsort($fruits);  // Sorts the fruits by their values in descending order
var_dump($fruits);
?>

/*
Output:
array(3) {
  ["Cherry"]=>
  string(1) "6"
  ["Apple"]=>
  string(1) "4"
  ["Banana"]=>
  string(1) "2"
}
*/

krsort()

<?php
$fruits = array("Apple" => "4", "Banana" => "2", "Cherry" => "6");
krsort($fruits);  // Sorts the fruits by their keys in reverse order
var_dump($fruits);
?>

/*
Output:
array(3) {
  ["Cherry"]=>
  string(1) "6"
  ["Banana"]=>
  string(1) "2"
  ["Apple"]=>
  string(1) "4"
}
*/

PHP - Multidimensional Arrays

A multidimensional array is an array that contains one or more arrays nested within it.

PHP supports multidimensional arrays that can be many levels deep. However, arrays deeper than three levels can be challenging for many users to manage.

The dimension of an array indicates the number of indices required to select an element, for example:

  • For a two-dimensional array, you need two indices to select an element.
  • For a three-dimensional array, you need three indices to select an element.

PHP - Two-dimensional Arrays

A two-dimensional array is an array of arrays .

Consider the following table.

<?php
Name          Stock  Sold
Apple         30     25
Banana        20     15
Cherry        10     7
Grapes        25     20
?>

We can store the data from the table above in a two-dimensional array, as follows.

<?php
$fruits = array(
  array("Apple", 30, 25),
  array("Banana", 20, 15),
  array("Cherry", 10, 7),
  array("Grapes", 25, 20)
);
?>

Now, the two-dimensional $fruits array contains four arrays, and it is indexed by two dimensions: rows and columns.

To access elements in the $fruits array, you need to specify both indices (row and column).

<?php
echo $fruits[0][0].": In stock: ".$fruits[0][1].", sold: ".$fruits[0][2].".<br>";
echo $fruits[1][0].": In stock: ".$fruits[1][1].", sold: ".$fruits[1][2].".<br>";
echo $fruits[2][0].": In stock: ".$fruits[2][1].", sold: ".$fruits[2][2].".<br>";
echo $fruits[3][0].": In stock: ".$fruits[3][1].", sold: ".$fruits[3][2].".<br>";
?>

/*
Output:
Apple: In stock: 30, sold: 25.
Banana: In stock: 20, sold: 15.
Cherry: In stock: 10, sold: 7.
Grapes: In stock: 25, sold: 20. 
*/

We can also nest a for loop inside another for loop to access elements in the $fruits array (you still need to specify both indices).

<?php
for ($row = 0; $row < 4; $row++) {
  echo "<p><b>Row $row</b></p>";
    for ($col = 0; $col < 3; $col++) {
      echo $fruits[$row][$col] . ", ";
    }
}
?>

/*
Output:
Row 0
Apple, 30, 25,

Row 1
Banana, 20, 15,

Row 2
Cherry, 10, 7,

Row 3
Grapes, 25, 20,
*/

PHP Array Functions

PHP includes a set of built-in functions specifically designed for working with arrays.

They will be covered in our PHP functions guide.

Questions & Answers