PHP Functions - Searching, Traversing, and Displaying Arrays - Arrays: PHP 7 Complete Guide: Simple, Multi-dimensional, Associative, and Object Arrays (2016)

Arrays: PHP 7 Complete Guide: Simple, Multi-dimensional, Associative, and Object Arrays (2016)

Chapter 6. PHP Functions - Searching, Traversing, and Displaying Arrays

After completing this chapter, the student will be able to…

Create a simple PHP program to search an array for an existing value and/or key

Create a simple PHP program which will traverse through every element of an array without using a loop

Create a simple PHP program which will display contents of an array based on a filter

In this final chapter we will take a brief look at the PHP functions to search, traverse, and display arrays. Many of these functions work with multiple array types (single, multi-dimensional, and/or associative).

All descriptions of the following functions are provided by the on-line PHP manual available at www.php.net. Brief examples using each function and a description of the results of these examples are provided. These examples are only ment to get your feet wet. For a more detailed description of the functions shown, and for more examples, visit the on-line PHP manual.

Searching Arrays

array_count_values — counts all the values of an array

“Returns an array using the values of array as keys and their frequency in array as values.”

Syntax:

array array_count_values ( array $array )

Example:
$silly_array = array(“hey”, “hey”, “hey”, “what”, “is”, “this”, “unsure”, “unsure”);
print_r(array_count_values($silly_array));

Output:
Array

(

[hey] => 3

[what] => 1

[is] => 1

[this] => 1

[unsure] => 2

)

This example counts the frequency of the values in $silly_array. It creates an array that uses the value as an index and the frequency as the value.

array_column - returns the values from a single column in the input array.

“array_column() returns the values from a single column of the input, identified by the column_key. Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array.”

Syntax:

array array_column ( array $input , mixed $column_key [, mixed $index_key = null ] )

Example:

$customer_record = array (

array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'GA', 'zip_code' => 30001),

array('first_name' => 'Sally' , 'last_name' => 'Parisi' , 'address' => '101 South Street' , 'city' => 'Atlanta' , 'state' => 'GA' , 'zip_code' => 30001)

);

$first_names = array_column($customer_record, 'first_name');

print_r($first_names);

Output:

Array

(

[0] => Pete

[1] => Sally

)

In this example, all first names in the customer_array are returned.

In PHP 7 you can also specify an index in the second parameter.

Example:

$customer_record = array (

array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'GA', 'zip_code' => 30001),

array('first_name' => 'Sally' , 'last_name' => 'Parisi' , 'address' => '101 South Street' , 'city' => 'Atlanta' , 'state' => 'GA' , 'zip_code' => 30001)

);

$first_names = array_column($customer_record, 'first_name', ‘last_name’);

print_r($first_names);

Output:

Array

(

[Smith] => Pete

[Parisi] => Sally

)

In this example, the values in last_name, are used to populate the new keys (subscripts) which are returned from the function.

array_key_exists — checks if the given key or index exists in the array

“array_key_exists() returns TRUE if the given key is set in the array. key can be any value possible for an array index.”

Syntax:

bool array_key_exists ( mixed $key , array $array )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'GA', 'zip_code' => 30001);

if (array_key_exists('first_name', $first_array)) {

print "The 'first_name' is in the array";

}

Output:

The 'first_name' is in the array

This function eliminates the need to create a loop when searching for a key in an array.

array_keys — returns all the keys or a subset of the keys of an array

“array_keys() returns the keys, numeric and string, from the array.”

Syntax:

array array_keys ( array $array [, mixed $search_value = null [, bool $strict = false ]] )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'GA', 'zip_code' => 30001);

print_r(array_keys($first_array));

Output:

Array (

[0] => first_name

[1] => last_name

[2] => address

[3] => city

[4] => state

[5] => zip_code

)

This example returns all keys that exist in array $first_name.

array_search — searches the array for a given value and returns the corresponding key if successful

“Searches haystack for needle.”

Syntax:

mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'GA', 'zip_code' => 30001);

print array_search('123 Main Street', $first_array);

Output:

address

The value passed has to be an exact match. Passing ‘Main’ only in this example would not return a match.

in_array — checks if a value exists in an array

“Returns TRUE if needle is found in the array, FALSE otherwise.”

Syntax:

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

if(in_array("Pete",$first_array))

{

print "Found Pete!";

}

else

{

print "WE LOST PETE!";

}

Output:

Found Pete!

in_array returns TRUE if the item searched is in the array. It does not return the position of the item in the array. In this example, Pete is found in the array.

key_exists — alias of array_key_exists()

“key_exists — Checks if the given key or index exists in the array”

Syntax:

bool key_exists ( mixed $key , array $array )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'GA', 'zip_code' => 30001);

if (key_exists('first_name', $first_array)) {

print "The 'first_name' is in the array";

}

Output:

The 'first_name' is in the array

This function eliminates the need to create a loop when searching for a key in an array.

Traversing Arrays

current — returns the current element in an array

“The current() function simply returns the value of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, current() returns FALSE.”

Syntax:

mixed current ( array &$array )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

print current($first_array) . "<br>";

print next($first_array) . "<br>";

print prev($first_array) . "<br>";

print end($first_array) . "<br>";

Output:

Pete

Smith

Pete

30001

current works with next, previous, and end to display values located in positions in an array. current does not actually move the pointer (position currently accessed) in the array. As shown in this example, only the values are displayed not the keys (subscripts).

each — returns the current key and value pair from an array and advance the array cursor

“After each() has executed, the array cursor will be left on the next element of the array, or past the last element if it hits the end of the array. You have to use reset() if you want to traverse the array again using each.”

Syntax:

array each ( array &$array )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

print_r(each($first_array));

print_r(each($first_array));

Output:

Array (

[1] => Pete

[value] => Pete

[0] => first_name

[key] => first_name

)

Array (

[1] => Smith

[value] => Smith

[0] => last_name

[key] => last_name

)

each will place the key from the current position in two different elements ([0] and [key]). It will also place the value in two different elements ([1] and [value]). It will also move the cursor (location in the array) to the next element. In this example, the key and value are pulled from the first position of the $first_name array. Then the cursor is moved to to the next element. The function is called again displaying the information from the second element. The cursor is now positioned at the third element.

end — sets the internal pointer of an array to its last element

“end() advances array's internal pointer to the last element, and returns its value.”

Syntax:

mixed end ( array &$array )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

print current($first_array) . "<br>";

print next($first_array) . "<br>";

print prev($first_array) . "<br>";

print end($first_array) . "<br>";

Output:

Pete

Smith

Pete

30001

In this example, end moves the cursor to the last element and returns the value in the element. The zip code is displayed.

key — fetches a key from an array

“The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way.”

Syntax:

mixed key ( array &$array )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

print key($first_array);

Output:

first_name

In this example, the array is currently at the top. key will display the key (subscript) at the current position. This function will not move the cursor.

next — advances the internal array pointer of an array

“next() behaves like current(), with one difference. It advances the internal array pointer one place forward before returning the element value. That means it returns the next array value and advances the internal array pointer by one.”

Syntax:

mixed next ( array &$array )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

print current($first_array) . "<br>";

print next($first_array) . "<br>";

print prev($first_array) . "<br>";

print end($first_array) . "<br>";

Output:

Pete

Smith

Pete

30001

Next moves to the next element and displays it. In this example current displays the first value (Pete) but does not advance to the next element. next advances to the next element and displays it (Smith).

pos — alias of current()

“The pos() function simply returns the value of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, pos() returns FALSE.”

Syntax:

mixed pos ( array &$array )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

print pos($first_array) . "<br>";

print next($first_array) . "<br>";

print prev($first_array) . "<br>";

print end($first_array) . "<br>";

Output:

Pete

Smith

Pete

30001

pos displays the current value but does not move to the next value. In this example pos will display Pete from the first position but will not move the cursor to the next position. next moves to the next position and displays the value (Smith).

prev — rewinds the internal array pointer

“prev() behaves just like next(), except it rewinds the internal array pointer one place instead of advancing it.”

Syntax:

mixed prev ( array &$array )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

print pos($first_array) . "<br>";

print next($first_array) . "<br>";

print prev($first_array) . "<br>";

print end($first_array) . "<br>";

Output:

Pete

Smith

Pete

30001

In this example, pos displays the first value (Pete). next moves to the next value and displays it (Smith). Prev moves back a position (back to the first position) and displays the value (Pete).

reset — sets the internal pointer of an array to its first element

“reset() rewinds array's internal pointer to the first element and returns the value of the first array element.”

Syntax:

mixed reset ( array &$array )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

print pos($first_array) . "<br>";

print next($first_array) . "<br>";

print reset($first_array) . "<br>";

print end($first_array) . "<br>";

Output:

Pete

Smith

Pete

30001

reset moves the pointer to the top of the array. In this example, pos returns value in the first element, but does not move the pointer. Next moves the pointer to the second element and then returns the value store in it. reset moves back to the top of the array and returns the value in the first element. end is the reverse of reset, it moves to the last position of the array and returns the value in that position.

Displaying Array Contents

array_map — applies the callback to the elements of the given arrays

“array_map() returns an array containing all the elements of array1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()”

Syntax:

array array_map ( callable $callback , array $array1 [, array $... ] )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'GA', 'zip_code' => 30001);

function add_info($value)

{

return("This value is " . $value);

}

print_r(array_map("add_info", $first_array));

Output:

Array (

[first_name] => This value is Pete

[last_name] => This value is Smith

[address] => This value is 123 Main Street

[city] => This value is Atlanta [state] =>

This value is GA

[zip_code] => This value is 30001

)

The function will apply changes to each element, as shown in the function passed (add_info), to the array passed to produce a new array with the keys intact. In this example This value is is appended to the value of each position in the array to produce a new array.

array_product — calculates the product of values in an array

“array_product() returns the product of values in an array.”

Syntax:

number array_product ( array $array )

Example:

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

print array_product($product);

Output:

3628800

In this example will multiply:

1 x 2 x 3 x 4 x 5 x 6 x 7 x 8 x 9 x 10 = 362880

array_rand — Pick one or more random entries out of an array

“Picks one or more random entries out of an array, and returns the key (or keys) of the random entries.”

Syntax:

mixed array_rand ( array $array [, int $num = 1 ] )

Example:

$first_array = array('Pete' , 'Smith' , '123 Main Street' , 'Atlanta', 'GA', '30001');

print_r (array_rand($first_array, 2));

Output:

Array (

[0] => 3

[1] => 5

)

In this example array_rand picks the third element (Atlanta) and the fifth element (30001) because 2 elements were requested.

array_reduce — iteratively reduces the array to a single value using a callback function

“array_reduce() applies iteratively the callback function to the elements of the array, so as to reduce the array to a single value.”

Syntax:

mixed array_reduce ( array $array , callable $callback [, mixed $initial = NULL ] )

Example:

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

function add($value, $number)

{

$value += $number;

return $value;

}

function subtract($value, $number)

{

$value -= $number;

return $value;

}

function multiply($value, $number)

{

$value *= $number;

return $value;

}

function divide($value, $number)

{

$value /= $number;

return $value;

}

print array_reduce($numerical_values, "add") . "<br>";

print array_reduce($numerical_values, "subtract") . "<br>";

print array_reduce($numerical_values, "multiply", -5) . "<br>";; // start with a $value of -5

print array_reduce($numerical_values, "divide", 5) . "<br>"; //start with a $value of 5

Output:

55

-55

-18144000

1.3778659611993E-6

array_reduce allows you to create your own function to traverse through an array, pick each item, and do something with the item. In these examples, functions are shown to add, subtract, multiple, and divide the items in the array.

print array_reduce($numerical_values, "multiply", -5) . "<br>";; // start with a $value of -5

This call starts with an initial value of -5 (which is placed in $value). The result (as seen above) is a negative value.

print array_reduce($numerical_values, "divide", 5) . "<br>"; //start with a $value of 5

This call starts with the 5 being placed into $value before each element value is divided.

array_sum — calculates the sum of values in an array

“Returns the sum of values as an integer or float.”

Syntax:

array_sum

Example:

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

print array_sum($sum);

Output:

55

In this example the values is the array are added together.

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

array_unique — removes duplicate values from an array

“Takes an input array and returns a new array without duplicate values.

Note that keys are preserved. array_unique() sorts the values treated as string at first, then will keep the first key encountered for every value, and ignore all following keys. It does not mean that the key of the first related value from the unsorted array will be kept.”

Syntax:

array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'GA', 'zip_code' => 30001, 'first_name' => 'Sally' , 'lastname' => 'Parisi' , 'address' => '101 South Street' , 'city' => 'Atlanta' , 'state' => 'GA' , 'zipcode' => 30001);

print_r(array_unique($first_array));

Output:

Array (

[first_name] => Sally

[last_name] => Smith

[address] => 101 South Street

[city] => Atlanta

[state] => GA

[zip_code] => 30001

[lastname] => Parisi

)

This function returns the first unique key for each value. In the example, once occurrence of each key is returned.

array_values — returns all the values of an array

“Returns an indexed array of values.”

Syntax:

array array_values ( array $array )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

print_r(array_values($first_array));

Output:

Array (

[0] => Pete

[1] => Smith

[2] => 123 Main Street

[3] => Atlanta

[4] => CA

[5] => 30001

)

array_values builds a numerical array of the values in the passed array. It does not retain the keys (subscripts) from the original array.

array_walk_recursive — applies a user function recursively to every member of an array

“Applies the user-defined callback function to each element of the array. This function will recurse into deeper arrays.”

Syntax:

bool array_walk_recursive ( array &$array , callable $callback [, mixed $userdata = NULL ] )

Example:

$customer_record = array (

'first_customer' =>

array('first_name' => 'Pete' , 'last_name' => 'Smith' ,

'address' => '123 Main Street' , 'city' => 'Atlanta',

'state' => 'GA', 'zip_code' => 30001),

'second_customer' =>

array('first_name' => 'Sally' , 'last_name' => 'Parisi' ,

'address' => '101 South Street' , 'city' => 'Atlanta' ,

'state' => 'GA' , 'zip_code' => 30001)

);

function print_customer_info($value, $key)

{

print " Customer $key is $value<br>";

}

array_walk_recursive($customer_record, 'print_customer_info');

Output:

Customer first_name is Pete

Customer last_name is Smith

Customer address is 123 Main Street

Customer city is Atlanta

Customer state is GA

Customer zip_code is 30001

Customer first_name is Sally

Customer last_name is Parisi

Customer address is 101 South Street

Customer city is Atlanta

Customer state is GA

Customer zip_code is 30001

Array_walk_recursive will apply anything within the programmer supplied function to each key and value in an array. As seen in this example, this function works well with multi-dimensional arrays.

array_walk — applies a user supplied function to every member of an array

“array_walk() is not affected by the internal array pointer of array. array_walk() will walk through the entire array regardless of pointer position.”

Syntax:

bool array_walk ( array &$array , callable $callback [, mixed $userdata = NULL ] )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' ,

'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA',

'zip_code' => 30001);

function print_customer_info($value, $key)

{

print " Customer $key is $value<br>";

}

array_walk($first_array, 'print_customer_info');

Output:

Customer first_name is Pete

Customer last_name is Smith

Customer address is 123 Main Street

Customer city is Atlanta

Customer state is CA

Customer zip_code is 30001

Array_walk will apply anything within the programmer supplied function to each key and value in the array. This function works best with single arrays as shown in the example.

count — counts all elements in an array, or something in an object

“Returns the number of elements in array_or_countable. If the parameter is not an array or not an object with implemented Countable interface, 1 will be returned.”

Syntax:

int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' ,

'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

print count($first_array);

Output:

6

count returns the number of elements (size) of the array. In this example, there are 6 elements. See sizeof for another example that can be used with count.

extract — imports variables into the current symbol table from an array

Syntax:

int extract ( array &$array [, int $flags = EXTR_OVERWRITE [, string $prefix = NULL ]] )

Example:

$first_array = array('first_name' => 'Pete' , 'last_name' => 'Smith' , 'address' => '123 Main Street' , 'city' => 'Atlanta', 'state' => 'CA', 'zip_code' => 30001);

extract($first_array);

print "The first name is " . $first_name . ". The last name is " . $last_name . ". The address is " . $address . ". The city is " . $city . ". The state is " . $state . ". The zip is " . $zip_code . ".";

Output:

The first name is Pete. The last name is Smith. The address is 123 Main Street. The city is Atlanta. The state is CA. The zip is 30001.

This function works with associative arrays. Variables (properties) are created using the key from the array. The values in the array are then placed into the properties. In this example six properties are created using the extract function.

sizeof — alias of count()

Syntax:

int sizeof ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )

Example:

$first_array = array('Pete' ,'Smith' ,'123 Main Street' ,'Atlanta', 'CA', 30001);

$count = sizeof($first_array);

for($I=0; $I < $count; $I++)

{

print $first_array[$I] . "<br />";

}

Output:

Pete

Smith

123 Main Street

Atlanta

CA

30001

sizeof will return the size of the array. Arrays are numbered starting at zero. The last position would be one less than the value returned. Thus, the for loop used above continues until $I is no longer less than the value in $count. Notice the example determines the size before the loop, instead of inside the for loop. This provides only one execution of the sizeof function instead of calling it seven times in the above example. See count for another example.

Exercises

1. Create a PHP program which containes an array if states in the United States. Use one of the existing functions in this chapter to find any state that begins with “M”.

2. Create a PHP program which includes the array from #1, traverse and display the contents of the array without using a loop.

3. Create a PHP program which includes the states and capitals of the United States. Using one of the PHP functions from this chapter, display a message similar to the following for each state:

“The capital of Georgia is Atlanta”.

Do not use any loops.