Demonstrate Arrays in PHP

This article demonstrates arrays in PHP. An array is a collection of values of the same data type. In PHP the array concept goes further in the manner that in PHP an array stores each item as a key and value pair.

An array is a collection of values of the same data type. In PHP the array concept goes further in the manner that in PHP an array stores each item as a key and value pair. Keys can be numeric vales or can be associative (as a string). These numeric values determine the position of each item in the array.

Creating an Array in PHP

Numeric index example

$user=array(0=>"sandeep",1=>"rahul",2=>"pankaj");

Or

$user[0] = " sandeep";

$user[1] = " rahul";

$user[2] = " pankaj";

This stores values of multiple names in each index. If the index is not provided then it will automatically increment the index for continuous value assignment as in the following:

$user[] = " sandeep";

$user[] = " rahul";

$user[] = " pankaj";

Associative Index example

By associative index we provide a meaning to every index, like if we want to denote multiple countries by their nickname then it will be as follows:

$country=array("IND"=>"INDIA","US"=>"UNITED STATES");

Then we can access INDIA by referencing $country["IND"].

Multidimensional Array

We can create arrays of arrays, in other words multidimensional arrays. For example we can make a student's marks in various subjects as follows.

<?php

$student=array

(

"HINDI"=>array("marks"=>"96","grade"=>"1st"),

"ENGLISH"=>array("marks"=>"92","grade"=>"1st")

);

foreach($student as $subject=>$sub)

{

foreach($sub as $marks=>$number)

{

echo "$marks = "," $number ";

}

echo "

<br/>";

}

?>

The output will be as follows:

marks = 96 grade = 1st
marks = 92 grade = 1st

Here we can reference a single item as follows:

$student["HINDI"]["marks"]

This gives the output:

96

Here basically we use either a numeric or an associative index but the key features present here is an array pointer although we actually didn’t use it.

Get array element using list()

TList has the same functionality as an array. list() provides a convenient method to assign one by one a variable value in the list extracted from an array in just one operation. This is maybe usually used when extracting data from a database of from file.

The following is an example:

<?php

$array = [

["hello", "hey"],

["yes", "hello"],

];

foreach ($array as list($a, $b))

{

// $a contains the first element of the nested array,

// and $b contains the second element.

echo "A: $a; B: $b\n";

}

?>

The output is as follows:

A: hello; B: hey A: yes; B: hello

Explanation: Here we define a 2D array and its value is assigned one by one in the list and then we print those elements. If we simply implement it as in in the previous example.

For example we want to make an array that contain 6 numbers as in the following:

<?php

$id=range(1,6);

// Same as specifying $id = array(1, 2, 3, 4, 5, 6)

$id1=range(1,8,2);

$id2=range("A","Z",3);

foreach($id as $value)

echo "$value ";

echo "

<br/>";

foreach($id1 as $value)

echo "$value ";

echo "

<br/>";

foreach($id2 as $value)

echo "$value ";

?>

That gives the following output:

1 2 3 4 5 6
1 3 5 7
A D G J M P S V Y

Output Explanation: In the preceding example for $id we just provide a range from 1 to 6 and the difference between each number is 1 by default.
For $id1 we start from 1 to 8 but there is the difference between 2 that we provided to it.

For $id2 we print the range from A to Z and the difference between each character is 3. This difference and calculation is basically done on each character ASCII value.

The range() function not always increments the ASCII, it makes a loop from the start value to the end value.

Testing for an array

Sometimes we need to verify whether the given variable is an array. Then this can be verified using the built-in function is_array(). It’s syntax looks as follows.

Boolean is_array(variable)

The preceding function returns true if the passed variable is an array else it returns false.

<?php

$states = array("Rajasthan");

$state = "Haryana";

printf("\$states is an array: %s

<br/>", (is_array($states) ? "TRUE" : "FALSE"));

printf("\$state is an array: %s

<br/>", (is_array($state) ? "TRUE" : "FALSE"));

?>

This gives the following output:

$states is an array: TRUE
$state is an array: FALSE

Outputting an array

The output of array's element can be done by iterating each key and this is simply accomplished by a foreach() loop. This can be as follows:

<?php

$id=range(6,1);

foreach($id as $value)

echo "$value ";

?>

This gives the following output:

6 5 4 3 2 1

For arrays of array elements we can use the vprintf() function that allows us to easily display array contents using the same formatting syntax used by the printf() and sprintf() functions. If we want to send the output to the string, in other words store it in a string then we can use the vsprintf() function as in the following:

<?php

$user = array();

$user[] = array("sandeep jangid", "sandeep@.com", "98989898");

$user[] = array("sanjeev baldia", "sanjeev@.net", "818546454");

$user[] = array("rahul prajapat", "rahul@.org", "212545485");

foreach ($user AS $customer)

{

vprintf("

<p>Name: %s

<br/>E-mail: %s

<br/>Phone: %s

</p>", $customer);

}

?>

This produces following output:

Name: sandeep jangid
E-mail: sandeep@.com
Phone: 98989898

Name: sanjeev baldia
E-mail: sanjeev@.net
Phone: 818546454

Name: rahul prajapat
E-mail: rahul@.org
Phone: 212545485

The print_r() function

The print_r() function accepts a variable and sends its contents to standard output, returning TRUE on success and FALSE otherwise. It is usually used for testing an array output. It makes an array content into readable format. It’s syntax looks like this.

boolean print_r(mixed variable [, boolean return])

The following:

<?php

$country=array("IND"=>"INDIA","US"=>"UNITED STATES");

print_r($country);

?>

Produces the following output:

Array ( [IND] => INDIA [US] => UNITED STATES )

If we want only to output the array values then this can be done using the optional parameter of print_r(variable, true) function to true otherwise false.

So if we use print_r($country,true) as in our previously example then it produces the following output:

INDIA UNITED STATES

Adding or removing array element

PHP provides a number of functions to shift, pop, push, shrink an array.

Those methods are:

array_unshift()=adds elements to the front of the array.

array_push()=adds values to the end of the array and returns the total count of the array element.

array_shift()=removes and returns the first item found in an array.

array_pop()=removes and returns the last element from an array.

Note: In all the preceding array functions, after performing any add and remove operation, the index values of the array will be modified depending on their respective function but associative keys never get a change.

Here search_value if included then only the keys that will be matched are shown. Setting the optional preserve_keys parameter to true will cause the array value's keys to be preserved in the returned array. The following:

To get an array’s current key value pair we can use the each() function that takes an array name as argument and automatically increments to the next key after retrieving the first key value pair. If the pointer is residing at the end of the array before executing each(), FALSE is returned.

To move an array pointer to the next position we use the next() function and to move an array pointer in the previous direction we use the prev() function. As we have already seen, the next() function example in the previous example.

Moving the Pointer to the First and Last Array Position

The reset() function sets an array pointer back to the beginning of the array. This function is commonly used when we need to review or manipulate an array multiple times within a script, or when sorting has completed whereas the end() function sets the array pointer to the last element of the array and returns that element.

The following:

<?php

$fruit=array("apple","mango","banana","orange");

$first=reset($fruit);

echo "$first ";

$last=end($fruit);

echo "$last";

?>

Produces the following output:

apple orange

Passing array values to a function

To pass an array’s values to a function we use the array_walk() function.

This function will pass each element of the array to a user-defined function.

This is useful when we want to perform specific kind of functions on each array element.

If we send an array as a reference then it will be completely changed for the entire scope.

Explanation: here we first define an associative array (we can also use an indexed array). Then we define a function sanitize_data() that takes the two parameters $value and $key. This $value and $key are obtained whenthe array_walk () function is called by sanitize_data() and passes $arr in the parameter. strip_tags() is a predefined function for concatenating strings.

If we are working with an array of arrays then we use the array_walk_recursive() function.

Determining the Size of an Array

The count() function returns the total number of values found in an array. The sizeof() function is similar to count(). Its syntax follows.

integer count(array array [, int mode]

If the optional mode parameter is enabled (set to 1), the array will be counted recursively. This is useful when counting all elements of a multidimensional array. The following example counts the total number of vegetables found in the $fruit array:

<?php

$fruit = array("mango", "apple", "orange", "pomegranate");

echo count($fruit);

?>

This returns the following:

4

The next example counts both the scalar values and array values found in $cities.

Recursively Appending Arrays: The array_merge_recursive() function merges two arrays. The same as done by the array_merge() function but the difference is when merging both arrays if there is more than one key/value pair in the array then it merges the values together and make the pre-existing key as it’s name.

A positive offset value will slice to begin offset positions from the beginning of the array. A negative offset value will slice offset positions from the end of the array. If the optional length parameter is absent, the slice will start at the offset and end at the last element of the array. If the length is provided and is positive, it will end at the offset + length position from the beginning of the array. Conversely, if length is provided and is negative, it will end at the count(input_array) – length position from the end of the array. If the optional parameter save_key is provided and set to true then the array key position will not be changed in the result.

The result of the array_intersect() is the array whose values is common to each array variable in another array. It considers the values to be identical if they have the same data type. For an associative array intersection we use the array_intersect_assoc() function.

Its syntax is as follows:

array array_intersect (array array1,array array2,…. Up to N)

For example:

<?php

$arrayarray1 = array("Oa", "Cz", "Nx", "Hu", "Cv");

$arrayarray2 = array("Oa", "sA", "Hu", "Nx", "Ia");

$arrayarray3 = array("Te", "Ma", "Nx", "Oa", "Hu");

$intersection = array_intersect($array1, $array2, $array3);

print_r($intersection);

?>

This produces the following output:

Array ( [0] => Oa [2] => Nx [3] => Hu )

Note: Just the opposite of array_intersect() we use the array_diff() function that returns the values located in the first array that are not located in any of the subsequent arrays and use the array_diff_assoc() function for the associative array.

The following is a list of the array related functions.

Function

Description

array()

Creates an array

array_change_key_case()

Changes all keys in an array to lowercase or uppercase

array_chunk()

Splits an array into chunks of arrays

array_column()

Returns the values from a single column in the input array

array_combine()

Creates an array using the elements from one "keys" array and one "values" array

array_count_values()

Counts all the values of an array

array_diff()

Compare arrays, and returns the differences (compare values only)

array_diff_assoc()

Compare arrays, and returns the differences (compare keys and values)

array_diff_key()

Compare arrays, and returns the differences (compare keys only)

array_diff_uassoc()

Compare arrays, and returns the differences (compare keys and values, using a user-defined key comparison function)

Compare arrays, and returns the matches (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)

array_uintersect_uassoc()

Compare arrays, and returns the matches (compare keys and values, using two user-defined key comparison functions)

array_unique()

Removes duplicate values from an array

array_unshift()

Adds one or more elements to the beginning of an array

array_values()

Returns all the values of an array

array_walk()

Applies a user function to every member of an array

array_walk_recursive()

Applies a user function recursively to every member of an array

arsort()

Sorts an associative array in descending order, depending on the value

asort()

Sorts an associative array in ascending order, depending on the value

compact()

Create array containing variables and their values

count()

Returns the number of elements in an array

current()

Returns the current element in an array

each()

Returns the current key and value pair from an array

end()

Sets the internal pointer of an array to its last element

extract()

Imports variables into the current symbol table from an array

in_array()

Checks if a specified value exists in an array

key()

Fetches a key from an array

krsort()

Sorts an associative array in descending order, depending on the key

ksort()

Sorts an associative array in ascending order, depending on the key

list()

Assigns variables as if they were an array

natcasesort()

Sorts an array using a case insensitive "natural order" algorithm

natsort()

Sorts an array using a "natural order" algorithm

next()

Advance the internal array pointer of an array

pos()

Alias of current()

prev()

Rewinds the internal array pointer

range()

Creates an array containing a range of elements

reset()

Sets the internal pointer of an array to its first element

rsort()

Sorts an indexed array in descending order

shuffle()

Shuffles an array

sizeof()

Alias of count()

sort()

Sorts an indexed array in ascending order

uasort()

Sorts an array by values using a user-defined comparison function

uksort()

Sorts an array by keys using a user-defined comparison function

usort()

Sorts an array using a user-defined comparison function

The preceding list of functions is referenced from www.w3schools.com.

Summary

Arrays are very important in programming. In PHP the functions provided for arrays are very useful for performing fast operations. Arrays can be used when taking values from a database or from a file and then use that data depending on our convenience.