PHP Array

PHP

In this tutorial we will learn about arrays in PHP.

What is an array?

An array is a single variable that can hold multiple values. Each value of an array is called an element of the array.

Array type in PHP

There are two type of arrays in PHP.

  • Index Array
  • Associative Array

Index Array

This is the array type in which each element is referenced by a numeric index which starts from 0. So, the first element is at index 0, the second element is at index 1 and so on.

Associative Array

This is the arry type in which each element is referenced by a string index. This type of are is also known as hash or map.

Creating an array

To create an array we use the array() function and pass the element in separated by comma.

To create an index array we use the following syntax.

$index_arr = array("Batman", "Superman", "Wonder Woman", "Justice League");

To create an associative array we use the following syntax.

$assoc_arr = array(
	"movie" => "Batman v Superman: Dawn of Justice",
	"director" => "Zack Snyder"
);

Accessing array elements

To access the element of an index array we use the numerical index.

$index_arr = array("Batman", "Superman", "Wonder Woman", "Justice League");

echo $index_arr[2];

The above code will print "Wonder Woman".

To access the element of an associative array we use the string index.

$assoc_arr = array(
	"movie" => "Batman v Superman: Dawn of Justice",
	"director" => "Zack Snyder"
);

echo $assoc_arr['movie'];

The above code will print "Batman v Superman: Dawn of Justice".

Adding elements to array

To add new elements to an index array we use the following syntax.

$index_arr = array("Batman", "Superman", "Wonder Woman", "Justice League");

//add new element
$index_arr[] = "Iron Man";

To add new elements to an associative array we use the following syntax.

$assoc_arr = array(
	"movie" => "Batman v Superman: Dawn of Justice",
	"director" => "Zack Snyder"
);

//adding release data
$assoc_arr['release'] = "March 25, 2016";

Change element of an array

To change any element of an index array we need to target it by its numeric index.

$index_arr = array("Batman", "Superman", "Wonder Woman", "Justice League");

//chaning the 4th element of the array
//remember array index starts from 0
$index_arr[3] = "Iron Man";

To change any element of an associative array we need to target it by its string index.

$assoc_arr = array(
	"movie" => "Batman v Superman: Dawn of Justice",
	"director" => "Zack Snyder",
	"release" => "2016"
);

//changing the release element
$assoc_arr['release'] = "March 25, 2016";

Output array - print_r()

We use the print_r() function to output the content of the array in detail.

In the following example we output the detail of index array using print_r().

$index_arr = array("Batman", "Superman", "Wonder Woman", "Justice League");

print_r($index_arr);

Output

Array (
	[0] => Batman
	[1] => Superman
	[2] => Wonder Woman
	[3] => Justice League
)

In the following example we output the detail of associative array using print_r().

$assoc_arr = array(
	"movie" => "Batman v Superman: Dawn of Justice",
	"director" => "Zack Snyder"
);

print_r($assoc_arr);

Output

Array (
	[movie] => Batman v Superman: Dawn of Justice
	[director] => Zack Snyder
)

Counting elements of an array - count()

We use the count() function to find the total number of elements in the array.

$index_arr = array("Batman", "Superman", "Wonder Woman", "Justice League");

echo count($index_arr);

The above code will print 4.

Looping through array using foreach()

To loop through all the elements of an array we can use the foreach loop.

In the following example we loop through index array using foreach loop.

$index_arr = array("Batman", "Superman", "Wonder Woman", "Justice League");

foreach ($index_arr as $elem) {
	printf("%s\n", $elem);
}

The above code will print all the elements of the index array $index_arr.

Batman
Superman
Wonder Woman
Justice League

In the following example we loop through associative array using the foreach loop.

$assoc_arr = array(
	"movie" => "Batman v Superman: Dawn of Justice",
	"director" => "Zack Snyder"
);

foreach ($assoc_arr as $key => $value) {
	printf("key = %s ---- Value = %s\n", $key, $value);
}

The above code will print all the elements using key value pair.

Key = movie ---- Value = Batman v Superman: Dawn of Justice
Key = director ---- Value = Zack Snyder

Creating multi dimensional array

To create a multi dimensional index array we use the following.

$m_index_arr = array(
	array(1, 2, 3),
	array(4, 5, 6),
	array(7, 8, 9)
);

print_r($m_index_arr);

In the above code we have created a 2D index array having 3 rows and 3 columns so, total 9 elements. And following is the output.

Array (
	[0] => Array (
		[0] => 1
		[1] => 2
		[2] => 3
	)
	[1] => Array (
		[0] => 4
		[1] => 5
		[2] => 6
	)
	[2] => Array (
		[0] => 7
		[1] => 8
		[2] => 9
	)
)

To create a multi dimensional associative array we use the following.

$m_assoc_arr = array(
	array(
		"movie" => "Batman v Superman: Dawn of Justice",
		"director" => "Zack Snyder"
	),
	array(
		"movie" => "Wonder Woman",
		"director" => "Patty Jenkins"
	),
	array(
		"movie" => "Justice League",
		"director" => "Zack Snyder"
	)
);

print_r($m_assoc_arr);

In the above code we have created a 2D associative array having 3 rows and 2 columns (movie, director) so, total 6 elements. And following is the output.

Array (
	[0] => Array (
		[movie] => Batman v Superman: Dawn of Justice
		[director] => Zack Snyder
	)
	[1] => Array (
		[movie] => Wonder Woman
		[director] => Patty Jenkins
	)
	[2] => Array (
		[movie] => Justice League
		[director] => Zack Snyder
	)
)

Accessing multi dimensional array using foreach()

To access multi dimensional index array we use the following.

$m_index_arr = array(
	array(1, 2, 3),
	array(4, 5, 6),
	array(7, 8, 9)
);

foreach ($m_index_arr as $row) {	//get each row

	foreach ($row as $elem) {		//get each element of the row
		printf("%d\n", $elem);
	}
}

To access multi dimensional associative array we use the following.

$m_assoc_arr = array(
	array(
		"movie" => "Batman v Superman: Dawn of Justice",
		"director" => "Zack Snyder"
	),
	array(
		"movie" => "Wonder Woman",
		"director" => "Patty Jenkins"
	),
	array(
		"movie" => "Justice League",
		"director" => "Zack Snyder"
	)
);

foreach ($m_assoc_arr as $row) {	//get the row
	
	foreach ($row as $key => $value) {	//get element of each row
		printf("%s = %s\n", $key, $value);
	}
}

Sort indexed array

To sort an indexed array in ascending order we use sort() function. This function will return true if sorting was successful. If there is any error then it will return false.

$index_arr = array("Batman", "Superman", "Wonder Woman", "Justice League");

sort( $index_arr );

print_r( $index_arr );

Output

Array ( [0] => Batman [1] => Justice League [2] => Superman [3] => Wonder Woman )

To sort the element in descending order we use the rsort() function.

$index_arr = array("Batman", "Superman", "Wonder Woman", "Justice League");

rsort( $index_arr );

print_r( $index_arr );

Output

Array ( [0] => Wonder Woman [1] => Superman [2] => Justice League [3] => Batman )

Sort associative array

To sort the associative array in ascending order and preserve the key we use the asort function.

$assoc_arr = array(
	"movie" => "Batman v Superman: Dawn of Justice",
	"director" => "Zack Snyder",
	"release" => "2016"
);

asort( $assoc_arr );

print_r( $assoc_arr );

Output

Array (
	[release] => 2016
	[movie] => Batman v Superman: Dawn of Justice
	[director] => Zack Snyder
)

If we use sort() function then key is lost.

$assoc_arr = array(
	"movie" => "Batman v Superman: Dawn of Justice",
	"director" => "Zack Snyder",
	"release" => "2016"
);

sort( $assoc_arr );

print_r( $assoc_arr );

Output

Array ( [0] => 2016 [1] => Batman v Superman: Dawn of Justice [2] => Zack Snyder )

So, we can see that the asort() function preserve the key of the associative array while sort function don't preserve.

In order to sort the associative array element in descending order we use arsort() function.

Sort associative array by key

In order to sort an associative array using key in ascending order we use the ksort() function.

$assoc_arr = array(
	"movie" => "Batman v Superman: Dawn of Justice",
	"director" => "Zack Snyder",
	"release" => "2016"
);

ksort( $assoc_arr );

print_r( $assoc_arr );

Output

Array (
	[director] => Zack Snyder
	[movie] => Batman v Superman: Dawn of Justice
	[release] => 2016
)

In order to sort an associative array using key in descending order we use krsort() function.

Add and remove elements

We use the array_push() function to add one or more elements at the end of the array.

$index_arr = array("Batman", "Superman");

array_push($index_arr, "Wonder Woman");

print_r($index_arr);

The above code will add "Wonder Woman" at the end of the $index_arr.

We use the array_pop() function to remove elements from the end of the array.

$index_arr = array("Batman", "Superman", "Iron Man");

echo array_pop($index_arr);		//this will print "Iron Man" as it is popped

print_r($index_arr);	//this will print only two elements.

To add one or more elements at the start of an array we use the array_unshift() function.

$index_arr = array("Batman", "Superman");

array_unshift($index_arr, "Wonder Woman", "Justice League");

print_r($index_arr);

The above code will add two elements at the start of the array.

To remove elements from the start of the array we use array_shift() function.

$index_arr = array("Iron Man", "Batman");

echo array_shift($index_arr);		//this will print "Iron Man"

print_r($index_arr);	//this will print only one element.

Get a portion of an array - array_slice()

This function takes 3 arguments. The first is the array variable, second is the start index and the last argument is the number of elements to take. This function will return a new array and the original array will remain same.

$index_arr = array("Batman", "Superman", "Wonder Woman", "Justice League");

$slice_arr = array_slice( $index_arr, 1, 2);

print_r( $slice_arr );

Output

Array (
	[0] => Superman
	[1] => Wonder Woman
)

Remove and Add elements using array_splice()

We use the array_splice() to remove a portion of an array and add elements to it.

This function takes 4 arguments.

The first argument is for the array.

The second argument is for the start index. If it is positive then start index is from the beginning of the input array. If it is negative then the start index is from the end of the input array.

The third argument is for the length. If it is positive then that many elements are removed. If it is negative then removed portion will be that many elements from the end of the input array. If the length is zero then no element is removed. And finally if the length is omitted then all elements from the start index is removed.

The fourth argument is for the replacement array.

Following are some examples.

Remove all the elements from the index 2.

$input = $input = array("Batman", "Superman", "Iron Man", "Wonder Woman", "Justice League");
array_splice($input, 2);

//Array ( [0] => Batman [1] => Superman)
print_r($input);

Remove all the elements from the index 2 from the end.

$input = array("Batman", "Superman", "Iron Man", "Wonder Woman", "Justice League");
array_splice($input, -2);

//Array ( [0] => Batman [1] => Superman [2] => Iron Man )
print_r($input);

Remove 1 element from index 2.

$input = array("Batman", "Superman", "Iron Man", "Wonder Woman", "Justice League");
array_splice($input, 2, 1);

//Array ( [0] => Batman [1] => Superman [2] => Wonder Woman [3] => Justice League )
print_r($input);

Remove 1 element from index 2 from the end.

$input = array("Batman", "Superman", "Iron Man", "Wonder Woman", "Justice League");
array_splice($input, -2, 1);

//Array ( [0] => Batman [1] => Superman [2] => Iron Man [3] => Justice League )
print_r($input);

Remove 1 element from index 2 and insert a new replacement.

$input = array("Batman", "Superman", "Iron Man", "Wonder Woman", "Justice League");

$repl_arr = array("Hulk");

array_splice($input, 2, 1, $repl_arr);

//Array ( [0] => Batman [1] => Superman [2] => Hulk [3] => Wonder Woman [4] => Justice League )
print_r($input);

Merge Array

We use the array_merge() function to merge two arrays.

In the following example we will merge two index array.

$movie1_arr = array("Batman", "Superman");
$movie2_arr = array("Wonder Woman", "Justice League");

$final_arr = array_merge($movie1_arr, $movie2_arr);

//Array ( [0] => Batman [1] => Superman [2] => Wonder Woman [3] => Justice League )
print_r($final_arr);

In the following example we will merge two associative array having different keys.

$movie1_arr = array(
	"movie" => "Batman v Superman: Dawn of Justice",
	"director" => "Zack Snyder"
);

$movie2_arr = array(
	"release" => "March 25, 2016"
);

$final_arr = array_merge($movie1_arr, $movie2_arr);

//Array ( [movie] => Batman v Superman: Dawn of Justice [director] => Zack Snyder [release] => March 25, 2016 )
print_r($final_arr);

The array_merge() function preserves the associative array keys.

In the following example we will merge two associative array having same keys. In this case the existing keys will be overwritten.

$movie1_arr = array(
	"movie" => "Batman v Superman: Dawn of Justice",
	"director" => "Zack Snyder"
);

$movie2_arr = array(
	"movie" => "Wonder Woman",
	"director" => "Patty Jenkins"
);

$final_arr = array_merge($movie1_arr, $movie2_arr);

//Array ( [movie] => Wonder Woman [director] => Patty Jenkins )
print_r($final_arr);

Array to String conversion

We use the implode() function to convert an array into string.

This function takes two arguments. First is the character to use to glue the elements of the array in the string and the second argument is the array to convert.

$movie = array("Batman", "Superman", "Wonder Woman");
$str = implode(" -- ", $movie);

//Batman -- Superman -- Wonder Woman
printf($str);

String to Array conversion

We use the explode() function to convert a string into array.

This function takes two argument. First is a set of characters to be used to split the string. Second argument is the string.

$str = "Batman,Superman,Wonder Woman,Justice League,Iron Man";

$arr = explode(",", $str);

//Array ( [0] => Batman [1] => Superman [2] => Wonder Woman [3] => Justice League [4] => Iron Man )
print_r($arr);

Array to list of variables conversion

We use the list() function to convert an array into a list of variables. Its a quick and easy way to assign values of an array to variables.

$arr = array("Batman v Superman: Dawn of Justice", "Zack Snyder");

list($movie, $director) = $arr;

//Movie = Batman v Superman: Dawn of Justice and Director = Zack Snyder
printf("Movie = %s and Director = %s", $movie, $director);