PHP TUTORIALPHP TutorialPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP CommentsPHP VariablesPHP Variable ScopePHP ConstantsPHP StringsPHP OutputPHP Data TypesPHP Type CastingPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP String FunctionsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP AdvancedPHP Include and RequirePHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms FinishingPHP OOPPHP OOP IntroductionPHP OOP ClassesPHP OOP PropertiesPHP OOP ObjectsPHP OOP MethodsPHP OOP $this KeywordPHP OOP Constructors and DestructorsPHP OOP VisibilityPHP OOP InheritancePHP OOP Abstract Classes and MethodsPHP OOP InterfacesPHP OOP TraitsPHP OOP ConstantsPHP OOP StaticPHP OOP NamespacesPHP OOP Autoloading

PHP Arrays

Arrays are variables that store multiple values.

PHP Why Arrays?

If you have a set of data (assume names of fruits) to store in variables what will you do? Like this?


<?php

$fruit1 = 'Apple';
$fruit2 = 'Banana';
$fruit3 = 'Orange';
$fruit4 = 'Mango';

If we needed to find the variable which has the value "Orange". What will you do? In this way, it is not that hard. But, if you had thousands of fruits how will you find that? It would be hard in this way. Arrays can be used to solve the problem.

Arrays are really useful when we work with lists (or data) of similar types.

Arrays in PHP

In PHP, arrays are commonly used for many purposes. An array in PHP can be considered as mapping a value to a key.

Arrays can have key/value pairs.

PHP Declaring an Array

In PHP, there are two ways to declare an array. (We have already discussed this in the data types chapter)

  • An array can be declared using the array() function.
  • An array can be declared wrapped with [ and ].

PHP Arrays Example


<?php
$array = array('Apple', 'Banana', 'Orange', 'Mango');
var_dump($array);

$array = ['Apple', 'Banana', 'Orange', 'Mango'];
var_dump($array);

Run Example ››

PHP Types of Arrays

There are three types of arrays in PHP.

PHP Indexed Arrays

Indexed arrays have numeric indexes or keys.

This is not a new thing for you. The array we created in the last step is an indexed array.


<?php
$fruits = ['Apple', 'Banana', 'Orange', 'Mango'];

In the above example, we do not specify the array keys (which are indexes).

Also, you can manually add the indexes.


<?php
$fruits[0] = 'Apple';
$fruits[1] = 'Banana';
$fruits[2] = 'Orange';
$fruits[3] = 'Mango';

Tip: Indexes starts from 0, not 1.

You can refer an element of the array as: $arrayName[index].

PHP Indexed Array Example


<?php
$fruits = ['Apple', 'Banana', 'Orange', 'Mango'];

echo "First Fruit is $fruits[0]" . '<br>';  
echo "Second Fruit is $fruits[1]" . '<br>';
echo "Third Fruit is $fruits[2]" . '<br>';
echo "Forth Fruit is $fruits[3]" . '<br>';

Run Example ››

PHP Associative Arrays

Associative arrays have named keys.

There are two ways to declare associative arrays.

  1. An associative array can be declared using the array() function or []
  2. 
    <?php
    $age = array(
    	'Joe' => 22,
    	'Adam' => 25,
    	'David' => 30
    );
    
    // or 
    
    $age = [
    	'Joe' => 22,
    	'Adam' => 25,
    	'David' => 30
    ];
    
    
    
  3. An associative array can be declared manually by adding keys.
  4. 
    <?php
    $age['Joe'] = 22;
    $age['Adam'] = 25;
    $age['David'] = 30;
    
    

In this example, we will save the age of persons (name as the key and age as the value). As we have named keys, this can be considered as an associative array.

PHP Associative Array Example


<?php
$age = array(
	'Joe' => 22,
	'Adam' => 25,
	'David' => 30
);
$age['Peter'] = 22;
$age['Christina'] = 25;

var_dump($age);

Run Example ››

Array keys can also be integers.

PHP Associative Array Example


<?php
$schedule = [
	16 => 'My Birthday',
	20 => 'Special Dinner',
	25 => 'PHP Conference'
];

Run Example ››

The difference between indexed arrays and the above associative arrays is that associative array is constructed by adding keys explicitly by us without any order (We didn't start from index 0).

PHP Multidimensional Arrays

Multidimensional arrays are arrays of arrays.

In PHP, you can store an array as the value of an array element. These types of arrays are called Multidimensional arrays as they have several stages (dimensions).


<?php
$people = [
	'Joe' => [
		'age' => 22,
		'country' => 'USA'
	],
	'Adam' => [
		'age' => 25,
		'country' => 'United Kingdom'
	], 
	'David' => [
		'age' => 30,
		'country' => 'France'
	]
];

PHP Foreach Loop

In PHP, the foreach loop is used to loop through arrays.

Foreach Syntax

foreach ($array as $key => $value) {
	code to execute
}

Note: Here, $array is the variable that contains the array. In each loop iteration, the name of the key of the current element will be assigned to $key and value to $value.

foreach with Indexed Arrays

In indexed arrays, => $value part is omitted in the foreach loop.

PHP foreach with Indexed Arrays Example


<?php
$fruits = ['Apple', 'Banana', 'Orange', 'Mango'];

// foreach loop
foreach ($fruits as $fruit) {
	echo $fruit . '<br>';
}

Run Example ››

foreach with Associative Arrays

PHP foreach with Associative Arrays Example


<?php
$people = [
	'Joe' => 22,
	'Adam' => 25,
	'David' => 30
];

foreach ($people as $name => $age) {
	echo "My name is $name, and age is $age" . '<br>';	
}

Run Example ››

foreach with Multidimensional Arrays

When working with databases, we will need to loop through multidimensional arrays frequently. As we do not explain database functions, let's take an example multidimensional array (which is like rows selected from a table) and loop through it to create a human-readable output.

PHP foreach with Multidimensional Arrays Example


<?php
$data = [
	'Game of Thrones' => ['Jaime Lannister', 'Catelyn Stark', 'Cersei Lannister'],
	'Black Mirror' => ['Nanette Cole', 'Selma Telse', 'Karin Parke']
];
echo '<h1>Famous TV Series and Actors';
foreach ($data as $series => $actors) {
	echo "<h2>$series</h2>";
	foreach ($actors as $actor) {
		echo "<div>$actor</div>";
	}
}

Run Example ››
  • In the first foreach, we loop though the data. In the first loop, $series is Game of Thrones and $actors is an indexed array of actor names
  • Inside the loop, we loop again through the $actors array and output the values.
  • The same thing happens again.

Playing with PHP Arrays

As arrays are commonly used with PHP, there are some "tricks" you need to learn. There are many array functions that do different operations on arrays. Here we will learn the most used ones.

1. Adding New Elements to Arrays (Using Brackets)

We can add a new element to the end of an array as follows.


<?php
$fruits = ['Apple', 'Banana', 'Orange', 'Mango'];

// add new elements to the end
$fruits[] = 'Pears';
$fruits[] = 'Watermelon';

var_dump($fruits);

Run Example ››

2. Adding New Elements to Arrays (Using array_push)

The array_push() function can be used to add new elements to an array. In this function, you can add multiple elements at the end at the same time.


<?php
$fruits = ['Apple', 'Banana', 'Orange', 'Mango'];

# add new elements
array_push($fruits, 'Pears', 'Watermelon');

var_dump($fruits);

Run Example ››

3. Prepending New Elements to Arrays

The array_unshift() function is used to prepend elements to an array. After prepending, array indexes will be changed accordingly. See this example.


<?php
$indexedArray = ['USA', 'UK', 'Canada'];
var_dump($indexedArray); // 0 => USA
array_unshift($indexedArray, 'Australia', 'New Zealand');
var_dump($indexedArray); // 0 => Australia

Run Example ››

You can see the indexes have changed after adding new elements to the beginning of the array.

4. PHP Getting the Length of an Array

The count() function is used to get the length of an Array in PHP.


<?php
$fruits = ['Apple', 'Banana', 'Orange', 'Mango'];
echo count($fruits); // will return 4

echo '<br>';

$age = array(
	'Joe' => 22,
	'Adam' => 25,
	'David' => 30
);
echo count($age); // will return 3;

Run Example ››

5. PHP Merging Two Arrays

The array_merge() function can be used to merge two arrays.


<?php
$array1 = ['red', 'blue'];
$array2 = ['yellow', 'green'];

$arrayMerged = array_merge($array1, $array2);
var_dump($arrayMerged);

Run Example ››

This function will add new indexes for indexed arrays, and it will overwrite the same keys for associative arrays.

The array union operator (+) can be used to merge two arrays when you have different keys.


<?php
$array1 = ['name' => 'John', 'age' => 24];
$array2 = ['country' => 'UK'];

$arrayMerged = $array1 + $array2;
var_dump($arrayMerged);

Run Example ››

6. PHP is_array()

is_array() checks if a variable is an array.


<?php
$int = 1;
$string = 'String';
$array = ['This', 'is', 'an', 'array'];

var_dump(is_array($int)); 	// false
var_dump(is_array($string));// false
var_dump(is_array($array));	// true

Run Example ››

7. PHP Check if an element exists in an array - in_array()

in_array() checks if a specific element is there in the given array.


<?php
$array = ['James', 'Doe', 'John'];
if (in_array('James', $array)) {
	echo "James is in the array";
}

Run Example ››

8. Check if a key exists in an array - array_key_exists()

array_key_exists() function checks if a specific key exists in an array.


<?php
$array = [
	'name' => 'William',
	'age' => 25,
	'country' => 'N/A'
];
var_dump( array_key_exists('name', $array) );  // true	
var_dump( array_key_exists('birthday', $array) );  // false

Run Example ››

10. Get the Array Values - array_values()

The array_values() function is used to get the array values as an indexed array.


<?php
$array = [
	'name' => 'William',
	'age' => 25,
	'country' => 'N/A'
];
$values = array_values($array);
var_dump($values);

Run Example ››

10. Get the Array Keys - array_keys()

The array_keys() function is used to get the array keys as an indexed array.


<?php
$array = [
	'name' => 'William',
	'age' => 25,
	'country' => 'N/A'
];
$keys = array_keys($array);
var_dump($keys);

Run Example ››

11. A Function on Each Element - array_map()

We can perform a function on each element and return a new array using the array_map() function.


<?php
$array1 = [24, 12, 45, 23];
$array2 = array_map(function($val) {
	return $val * 2;
}, $array1);
var_dump($array2);

Run Example ››

The above example will create a new array ($array2) from $array1 where each value is multiplied by 2.

  • The first argument is the array we are going to perform the function on.
  • The second argument is the callback function. The value of each element is sent to the function and we need to return the processed value. It will be saved in the new array.

Here we learned the basic array functions that are frequently used. But, there is a huge number of array functions for different tasks. When you are developing your PHP applications, you will need to learn more about PHP array functions to make life easier. Keep in that PHP manual is your friend; see Array Functions.

Need help with PHP? Post your question on our forum's PHP Group.
Facebook Twitter