PHP Arrays

Last Updated : May 22, 2021

PHP Arrays are used to store more than one value in a single Variable. For example, if you want to store similar pattern values like 100 flower names in a single variable, then you can use array data type to store the values. In Array, the key is used to get the corresponding value because the array is a key-value pair representation, and the key can be integer or string data types.

How to create/declare an Array in PHP?

In PHP, an array can be declared using array() function and open/close bracket [] short form. PHP 7 version supports both formats of array declaration and treated in the same way. Please find them below,

  • array()
  • []

Please find below the example of array creation,

<?php
$first_array = array('one', 'two', 'three');
print '<pre>'; print_r($first_array); print '</pre>';

$second_array = ['one', 'two', 'three'];
print '<pre>'; print_r($second_array); print '</pre>';
?>

Types of Array in PHP

In PHP, Array is categorized into three major types based on its key-value type and storage format. Please find below the list of types, and we will learn about them in detail below.

Numeric Indexed Array in PHP

Numeric Indexed array is one of the common array types in PHP that can store any type of values, but their index will always be numeric. This array index value starts with 0 and increases by 1 based on the total elements count of the array. When you initialize an array using the array() syntax with value, it will create an indexed array by default. Please find below the examples,

<?php
//exmaple-1
$first_array = array('one', 'two', 'three', 'four', 'five');
print '<pre>'; print_r($first_array); print '</pre>';

//example-2
$second_array[0] = 'one';
$second_array[1] = 'two';
$second_array[2] = 'three';
$second_array[3] = 'four';
$second_array[4] = 'five';
print '<pre>'; print_r($second_array); print '</pre>';

//eample-3
$third_array[] = 'one';
$third_array[] = 'two';
$third_array[4] = 'three';
print '<pre>'; print_r($third_array); print '</pre>';
?>

TIP: Array’s index always starts from 0, not 1 or any other value.

Associative Array in PHP

Associative Array in PHP is very similar to Indexed Array type, but the major difference is that Associative array used to store values with a user-defined custom key. The custom key will be associated with a specific value to refer to that value easily for processing. Please find below the examples,

<?php
//example-1
$students_department = array(
                         'John' => "Computer Science",
                         'Peter' => "Science",
                         'Dan' => "History"
                        );
print '<pre>'; print_r($students_department); print '</pre>';

//example-2
$students_department['George'] = "Physics";
$students_department['Michael'] = "Maths";
$students_department['Donald'] = "Chemistry";
echo $students_department['George'].'<br>';
print '<pre>'; print_r($students_department); print '</pre>';
?>

Multidimensional Array in PHP

Multidimensional Array in an array that can be Indexed or Associated array, but at least one key contains another array as its value. The above Indexed and Associative array’s key must have value, but the value may be from a numeric, string data type.

Whereas in Multidimensional array, the key contains Indexed, Associative, or another Multidimensional array itself as a value. It is a kind of array that will have multiple arrays inside and may have more than one dimension of data. Please find below the examples,

<?php
$students = array (
                   'John' => array('department' => "History", 'grade' => 'A+'),
                   'Peter' => array('department' => "Science", 'grade' => 'A+'),
                   'George' => array('department' => "Physics", 'grade' => 'A'),
                   'Michael' => array('department' => "Maths", 'grade' => 'A+'));

print '<pre>'; print_r($students); print '</pre>';

//another way to display
foreach($students as $student => $result) {
	echo $student.' is '. $result['department'].
		' student and his grade is '.$result['grade'] .'<br>';
}
?>

Top 10 useful Array Functions in PHP

There are a bunch of Array functions are available in PHP. We will learn about them in detail in the Function reference section. Please find below the most commonly used Array functions,

count() – counts an array

The count() function is used to count elements available inside an array and returns the length of an as output.

<?php
$array = array('one', 'two', 'three');
echo count($array);
?>

sort() – sorts an array in ascending order

This sort() function is used to sort an array numerically or alphabetically in an ascending order based on its value.

<?php
//example-1
$array = array('Banana', 'Apple', 'Orange');
sort($array);
print '<pre>'; print_r($array); print '</pre>';

//exmaple-2
$array = array(5, 500, 10, 100, 55, 11);
sort($array);
print '<pre>'; print_r($array); print '</pre>';
?>

rsort() – sorts an array in descending order

This rsort() function is used to sort an array numerically or alphabetically in a descending order based on its value.

<?php
//example-1
$array = array('Banana', 'Apple', 'Orange');
sort($array);
print '<pre>'; print_r($array); print '</pre>';

//exmaple-2
$array = array(5, 500, 10, 100, 55, 11);
sort($array);
print '<pre>'; print_r($array); print '</pre>';
?>

There are few more array sorting functions available in PHP, we will learn about them in detail in the later chapter.

is_array() – checks if a variable is an array

This is_array() function is used to check a given variable is an array or not, returns boolean true or false as output.

<?php
$array = array('Apple', 'Banana', 'Orange');
var_dump(is_array($array));
echo '<br>';

$array_1 = 42;
var_dump(is_array($array_1));
?>

in_array() – checks if value available in the array

This in_array() function is used to check the given element value is available inside an array and returns boolean true or false as output.

<?php
$array = ['Cat', 'Dog', 'Tiger', 'Lion'];
if(in_array('Lion', $array)) {
   echo "Lion is availabe in an array <br>";
}

if(in_array('Elephant', $array)) {
   echo "Elephant is availabe in an array";
} else {
   echo "Elephant is not availabe in an array";
}
?>

array_push() – used to push element to an array

This array_push() function is used to add a new element to an existing array, and it will be added at the end of the array by default.

<?php
$animals = ['Cat', 'Dog', 'Tiger', 'Lion'];
array_push($animals, 'Elephant');
print '<pre>'; print_r($animals); print '</pre>';

array_push($animals, 'Kangaroo', 'Zebra');
print '<pre>'; print_r($animals); print '</pre>';
?>

array_merge() – used to merge two arrays

This array_merge() function is used to merge two array elements and create a new array.

<?php
$animals = ['Cat', 'Dog', 'Tiger', 'Lion'];
$birds = ['Parrot', 'Sparrow', 'Dove']

$all = array_merge($animals, $birds);
print '<pre>'; print_r($all); print '</pre>';
?>

array_values() – get values from the array

This array_values() function is used to get all the values available in an array and returns the output as an indexed array.

<?php
$students_department = array(
                         'John' => "Computer Science",
                         'Peter' => "Science",
                         'Dan' => "History"
                        );
$departments = array_values($students_department);
print '<pre>'; print_r($departments); print'</pre>'; 
?>

array_keys() – get keys from the array

This array_keys() function is used to get all the keys available in an array and returns the output as an indexed array.

<?php
$students_department = array(
                         'John' => "Computer Science",
                         'Peter' => "Science",
                         'Dan' => "History"
                        );
$names = array_keys($students_department);
print '<pre>'; print_r($names); print'</pre>'; 
?>

range() – to create an array within the range

This range() function is used to create a new array of elements with a given range.

<?php
//example-1
$numbers = array(0, 10);
print '<pre>'; print_r($numbers); print'</pre>'; 

//example-2
$chars = array('a', 'f');
print '<pre>'; print_r($chars); print'</pre>'; 
?>

In this tutorial, we learned about different Arrays and their creation/manipulation using different built-in functions. We will learn about more useful Array functions with a detailed example later in this tutorial series.