আগামী ২৩ অক্টোবর -২০১৭ তারিখ থেকে শুরু হচ্ছে পাঁচ মাস ব্যাপী Professional Web Design and Development with HTML,CSS,Bootstrap,PHP,MySQl, AJAX and JQUERY কোর্সের ৮৬ তম ব্যাচ। আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করতে অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল: 01722817591, Email : [email protected] কোর্সের সিলেবাস এর জন্য এখানে ক্লিক করুন ।

Working With PHP Arrays

PHP Array

In this tutorial we will learn tips and tricks to use PHP array efficiently in Our PHP program. We also explain the PHP Array in details for beginners to advance programmers

Printing Arrays

Problem

You want to print the contents of an array.

Solution

Use PHP’s print_r() or var_dump() functions.

<?php

// define array

$data = array("UK" => array("longname" => "United Kingdom", "currency" => "GBP"),"US" => array("longname" => "United States of America", "currency" =>"USD"),"BD" => array("longname" => "Bangladesh", "currency" => "BDT"));

// print array contents

print_r($data);

var_dump($data);

?>

The print_r() and var_dump() functions are great ways to X-ray the contents of an array variable, and print a hierarchical listing of its internals. The above demonstrates them both in action. Note that var_dump() produces more verbose output (including information on data types and lengths) than print_r().

Processing Arrays

Problem

You want to iteratively process the elements in an array.

Solution
Use a foreach() loop and appropriate temporary variables, depending on whether the array has numeric indices or string keys:

<?php

// define indexed array

$idxArr = array("John", "Joe", "Harry", "Sally", "Mona");

// process and print array elements one by one

// result: "John | Joe | Harry | Sally | Mona | "

foreach ($idxArr as $i) {

print "$i | ";

}

?>

<?php

// define associative array

$assocArr = array("UK" => "London", "US" => "Washington","FR" => "Paris", "BD" => "Dhaka");

// process and print array elements one by one

// result: "UK: London US: Washington FR: Paris BD: Dhaka "

foreach ($assocArr as $key=>$value) {

print "$key: $value";

print "<br />";

}

?>

PHP’s foreach() loop is the simplest way to iterate over an array. At each iteration, the current array element is assigned to a temporary variable, which can then be used for further processing. For associative arrays, two temporary variables may be used, one each for the key and value.

Alternatively, you may prefer to use the Iterators available as part of the SPL. Iterators are ready-made, extensible constructs designed specifically to loop over

item collections—directories, files, class methods, and (naturally!) array elements. To process an array, use an ArrayIterator, as illustrated here:

<?php

// define associative array

$assocArr = array("UK" => "London", "US" => "Washington","FR" => "Paris", "BD" => "Dhaka");

// create an ArrayIterator object

$iterator = new ArrayIterator($assocArr);

// rewind to beginning of array

$iterator->rewind();

// process and print array elements one by one

// result: "UK: London US: Washington FR: Paris BD: Dhaka "

while($iterator->valid()) {

print $iterator->key() . ": " . $iterator->current() . "<br>";

$iterator->next();

}

?>

Here, an ArrayIterator object is initialized with an array variable, and the object’s rewind() method is used to reset the internal array pointer to the first element of the array. A while() loop, which runs so long as a valid() element exists, can then be used to iterate over the array. Individual array keys are retrieved with the key() method, and their corresponding values are retrieved with the current() method. The next() method moves the internal array pointer forward to the next array element. You can read more about the ArrayIterator at http://www.php.net/~helly/php/ext/spl/

Processing Nested Arrays

Problem

You want to process all the elements in a series of nested arrays.

Solution

Write a recursive function to traverse the array:

<?php

// function to recursively traverse nested arrays

function arrayTraverse($arr) {

// check if input is array

if (!is_array($arr)) {

die ("Argument is not array!");

}

// iterate over array

foreach($arr as $value) {

// if a nested array

// recursively traverse

if (is_array($value)) {

arrayTraverse($value);

}

else {

// process the element

print strtoupper($value) . "<br>";

}

}

}

// define nested array

$data = array("United States",array("Texas", "Philadelphia"),array("California",array ("Los Angeles", "San Francisco")));

// result: "UNITED STATES TEXAS PHILADELPHIA CALIFORNIA LOS ANGELES SAN FRANCISCO"

arrayTraverse($data);

?>

It’s fairly easy to iterate over a single array, processing each and every element in turn. Dealing with a series of nested arrays requires a little more effort. The previous listing illustrates the standard technique, a recursive function that calls itself to travel ever deeper into a layered array.

The inner workings of the arrayTraverse() function are fairly simple. Every time the function encounters an array value, it checks to see if that value is an array or a scalar. If it’s an array, the function calls itself and repeats the process until it reaches a scalar value. If it’s a scalar, the value is processed—the previous listing calls strtoupper(), but you can obviously replace this with your own custom routine—and then the entire performance is repeated for the next value. You could also use an Iterator from the SPL. Iterators are ready-made, extensible constructs designed specifically to loop over item collection—directories, files, class methods, and array elements. A predefined RecursiveArrayIterator already exists and it’s not difficult to use this for recursive array processing.

Here’s how:

<?php

// define nested array

$data = array("United States",array("Texas", "Philadelphia"),array("California",array ("Los Angeles", "San Francisco")));

// initialize an Iterator

// pass it the array to be processed

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));

// iterate over the array

// result: "UNITED STATES TEXAS PHILADELPHIA CALIFORNIA LOS ANGELES SAN FRANCISCO"

foreach ($iterator as $value) {

print strtoupper($value) . " <br>";

}

?>

To recursively process an array, initialize a RecursiveIteratorIterator object (this is an Iterator designed solely for the purpose of iterating over other recursive Iterators) and pass it a newly minted RecursiveArrayIterator. You can now process all the elements of the nested array(s) with a foreach() loop.

You can read more about the RecursiveArrayIterator, the RecursiveIteratorIterator, and the RecursiveIterator interfaces at http://www.php.net/~helly/php/ext/spl/.

Counting the Number of Elements in an Array

Problem

You want to find out how many elements an array contains.

Solution

Use PHP’s count() function:

<?php

// define indexed array

$animals = array("turtle", "iguana", "wolf", "anteater", "donkey");

// get array size (number of elements)

// result: 5

echo count($animals);

?>

The count() function returns the number of elements in the array. An alternative is to use the sizeof() function, which does the same thing.

Converting Strings to Arrays

Problem

You want to decompose a string into individual elements and store them in an array, or combine the elements of an array into a single string.

Solution

Use PHP’s explode() function to split a string by delimiter and store the separate segments in a numerically indexed array:

<?php

// define string

$alphabetStr = "a b c d e f g h i j k";

// break string into array

// using whitespace as the separator

// result: ("a","b","c","d","e","f","g","h","i","j","k")

print_r(explode(" ", $alphabetStr));

?>

Use PHP’s implode() function to combine array elements into a single string, with an optional delimiter as “glue”:

<?php

// define array

$names = array("John", "Joe", "Harry", "Sally", "Mona");

// combine array elements into string

// using "and" as the separator

// result: "John and Joe and Harry and Sally and Mona"

echo implode(" and ", $names);

?>

PHP’s explode() function makes it a single-step process to split a delimiterseparated string list into an array of individual list elements. The previous listing

clearly illustrates this: the explode() function scans the string for the delimiter and cuts out the pieces around it, placing them in an array. Once the list items have been extracted, a foreach() loop is a good way to process the resulting array. PHP’s implode() function does the reverse. It iterates over an array, joining the elements into a single string. An optional delimiter, typically a comma (,) or colon (:), can be used to separate the array elements from each other in the final string. The previous listing illustrates this by using the word “and” to join the various array elements into a readable sentence.

Swapping Array Keys and Values

Problem

You want to interchange the keys and values of an associative array.

Solution

Use PHP’s array_flip() function:

<?php

// define associative array

$opposites = array("white" => "black", "day" => "night", "open" =>"close");

// exchange keys and values

// returns ("black" => "white", "night" => "day", "close" => "open")

print_r(array_flip($opposites));

?>

PHP’s array_flip() function performs a very specialized task. It reverses the key-value relationship for all the elements of an associative array, returning a new array that is the mirror image of the original. This function should not be confused with the array_reverse() function, discussed in the listing in “4.12: Reversing Arrays.”

Adding and Removing Array Elements

Problem

You want to add or remove elements from an array.

Solution

Use PHP’s array_pop(), array_push(), array_shift(), and array_unshift() functions to attach or detach elements from the beginning or ends of a

numerically indexed array:

<?php

// define indexed array

$superheroes = array("spiderman", "superman");

// add an element to the end of the array

// result: ("spiderman", "superman", "the incredible hulk")

array_push($superheroes, "the incredible hulk");

print_r($superheroes);

// take an element off the beginning of the array

// result: ("superman", "the incredible hulk")

array_shift($superheroes);

print_r($superheroes);

// add an element to the beginning of the array

// result: ("the human torch", "superman", "the incredible hulk")

array_unshift($superheroes, "the human torch");

print_r($superheroes);

// take an element off the end of the array

// result: ("the human torch", "superman")

array_pop($superheroes);

print_r($superheroes);

?>

Use PHP’s array_splice() function to add or remove elements from the middle of an array:

<?php

// define array

$colors = array("violet", "indigo", "blue", "green", "yellow","orange", "red", "purple", "black", "white");

// remove middle 4 elements

// result: ("violet", "indigo", "blue", "purple", "black", "white")

array_splice($colors, 3, 4);

print_r($colors);

// add 2 elements between "black" and "white"

// result: ("violet", "indigo", "blue", "purple", "black","silver", "brown", "white")

array_splice($colors, 5, 0, array("silver", "brown"));

print_r($colors);

?>

PHP comes with four functions to add and remove elements from the ends of an array. The array_unshift() function adds an element to the beginning of an

array, while the array_shift() function removes the first element of an array. The array_push() and array_pop() functions work in a similar manner,

but operate on the end of an array instead. Note that the array is automatically re-indexed after each operation.

Note: You can add multiple elements with array_unshift() and array_push()—simply specify them as additional arguments in the function call.

Comment: It is not usually appropriate to use the array_unshift() and array_push()functions with associative arrays. Elements added in this manner will have numeric, rather than string, indices.

To add or remove elements from the middle of an array, use the array_splice() function. This function packs a lot of power under an unassuming exterior—it can be used to “splice in” new array elements, optionally replacing existing elements in the process.

The array_splice() function accepts four arguments: the array to operate on, the index to begin splicing at, the number of elements to return from the start

position, and an array of replacement values. Omitting the final argument causes array_splice() to remove elements without replacing them; this comes in

handy for removing elements from the middle of an array. Note that the array is automatically re-indexed after array_splice() has finished.

TIP:

You can actually use array_splice() to perform all the functions of array_pop(),array_push(), array_shift(), and array_unshift(). The PHP manual page at http://www.php.net/array-splice has more information.

NOTE:

The array_unshift(), array_shift(), array_pop(), and array_push() functions only work with previously initialized arrays. You’ll get an error if you attempt to use them on uninitialized array variables.

Extracting Contiguous Segments of an Array

Problem

You want to retrieve two or more successive elements from an array.

Solution

Use PHP’s array_slice() function:

<?php

// define array

$colors = array("violet", "indigo", "blue", "green", "yellow","orange", "red", "purple", "black", "white");

// extract middle 4 elements

// result: ("green", "yellow", "orange", "red");

$slice = array_slice($colors, 3, 4);

print_r($slice);

?>

Comments

PHP enables you to extract a subsection of an array with the array_slice()function, in much the same way that the substr() function enables you to extract a section of a string. The function takes three arguments: the array variable to operate on, the index to begin slicing at, and the number of elements to return from the start position. It’s important to note that array_slice() is less intrusive than the array_splice() function discussed in the listing in “4.7: Adding and Removing Array Elements”—array_splice() alters the original array, while array_slice() merely returns a subset, leaving the original array unchanged.

Removing Duplicate Array Elements

Problem

You want to strip an array of all duplicate elements to obtain a unique set.

Solution

Use PHP’s array_unique() function:

<?php

// define an array containing duplicates

$numbers = array(10,20,10,40,35,80,35,50,55,10,55,30,40,70,50,10,35,85,40,90,30);

// extracts all unique elements into a new array

// result: "10, 20, 40, 35, 80, 50, 55, 30, 70, 85, 90"

echo join(", ", array_unique($numbers));

?>

Comments

The array_unique() function is an easy way to produce a list of the unique elements of an array. This function finds all the unique elements of an array (either

associative or numerically indexed) and places them into a new array. The original array remains unchanged. To filter array elements by other criteria, take a look at the listing in “Filtering Array Elements.”

Re-indexing Arrays

Problem

You want to re-index a numerically indexed array after removing elements from it, to close up the “gaps” in the indexing sequence.

Solution

Use PHP’s array_values() function:

<?php

// define indexed array

$superheroes = array(0 => "spiderman", 1 => "superman",2 => "captain marvel", 3 => "green lantern");

// remove an element from the middle of the array

// result: (0 => "spiderman", 1 => "superman", 3 => "green lantern")

unset ($superheroes[2]);

// rearrange array elements to remove gap

// result: (0 => "spiderman", 1 => "superman", 2 => "green lantern")

$superheroes = array_values($superheroes);

print_r($superheroes);

?>

If you remove one or more elements from the middle of an integer-indexed array with the unset() function, PHP doesn’t automatically re-index the array for you. As a result, you end up with an array containing nonsequential index numbers. It’s generally a good idea to close up these “holes” in the array indexing sequence, to eliminate the possibility of them skewing your array calculations. The simplest way to do this is to retrieve the list of array values with the array_values()function, and then reassign this list back to the original array variable. This reindexes the array and closes up the gaps.

NOTE:

Because associative arrays use string indices, you don’t need to re-index them in this manner after unset()-ting their elements.

Randomizing Arrays

Problem

You want to shuffle an array randomly, or retrieve one or more random elements from an array.

Solution

Use PHP’s shuffle() and array_rand() functions:

<?php

// define array of numbers from 1 to 5

$numbers = range(1,5);

// shuffle array elements randomly

// result: "3, 5, 1, 2, 4" (example)

shuffle($numbers);

echo join (", ", $numbers);

?>

<?php

// define array of numbers from 1 to 12

$numbers = range(1,12);

// pick 5 random keys from the array

$randKeys = array_rand($numbers, 5);

// print the chosen elements

// result: "3, 5, 1, 2, 4" (example)

echo join (", ", $randKeys);

?>

PHP’s shuffle() function randomly re-arranges the elements of the array passed to it. Key-value associations are retained for associative arrays, but not for

numerically indexed arrays. If you’d prefer to leave the array order untouched and just pull out some elements at random instead, the array_rand() function is a better bet. This function returns an array of randomly extracted keys, which you can then use to retrieve the corresponding array values.

Reversing Arrays

Problem

You want to reverse the order of elements in an array.

Solution

Use PHP’s array_reverse() function:

<?php

// define array of numbers

$numbers = array("one", "two", "three", "four", "five");

// return an array with elements reversed

// result: ("five", "four", "three", "two", "one")

print_r(array_reverse($numbers));

?>

PHP’s array_reverse() function is pretty simple—give it an array and it returns a new array containing the elements of the original array, but in reverse order. Keyvalue association is retained for associative arrays, but numerically indexed arrays are re-indexed.

Searching Arrays

Problem

You want to search an array for a particular key or value.

Solution

Use PHP’s array_key_exists() or in_array() functions:

<?php

// define associative array

$data = array(

"UK" => "United Kingdom",

"US" => "United States of America",

"IN" => "India",

"AU" => "Australia");

// search for key

// result: "Key exists"

echo array_key_exists("UK", $data) ? "Key exists" :"Key does not exist";

// search for value

// result: "Value exists"

echo in_array("Australia", $data) ? "Value exists" :"Value does not exist";

?>

PHP comes with two functions that let you search both array keys and values: the array_key_exists() function scans an array’s keys for matches to your search term, while the in_array() function checks its values. It should be noted, though, that the search capability here is fairly primitive; both functions will return false unless they find an exact match for your search term.

If you need more sophisticated search capabilities—for example, support for regular expression or partial matches—consider writing your own search function, as in the script that follows:

<?php

// function to search array keys and values

function arraySearch($needle, $haystack) {

// check if input is array

if (!is_array($haystack)) { die ("Second argument is not array!"); }

// iterate over array

foreach ($haystack as $key=>$value) {

// check keys and values for match

// return true if match

if (preg_match("/$needle/i", $value) || preg_match("/$needle/i", $key)) {

return true;

break;

}

}

}

// define associative array

$data = array(

"UK" => "United Kingdom",

"US" => "United States of America",

"BD" => "Bangladesh",

"AU" => "Australia");

// search array

// returns "Match"

echo arraySearch("us", $data) ? "Match" : "No match";

// returns "No match"

echo arraySearch("xz", $data) ? "Match" : "No match";

?>

Here, the preg_match() function is used to search both keys and values of an array for a match. You can, of course, modify this to suit your own requirements.

NOTE: The arraySearch() function described here will not work correctly with multidimensional arrays. To recursively search a multidimensional array, flip forward to the listing in “Searching Nested Arrays.”

Searching Nested Arrays

Problem

You want to search a series of nested arrays for a particular key or value.

Solution

Write a recursive function to traverse the arrays and run a custom search function on each element:

<?php

// function to recursively traverse nested arrays

// and search for values matching a pattern

function arraySearchRecursive($needle, $haystack, $path="") {

// check if input is array

if (!is_array($haystack)) { die ("Second argument is not array!"); }

// declare a variable to hold matches

global $matches;

// iterate over array

foreach($haystack as $key=>$value) {

if (preg_match("/$needle/i", $key)) {

$matches[] = array($path . "$key/", "KEY: $key");

}

if (is_array($value)) {

// if a nested array

// recursively search

// unset the path once the end of the tree is reached

$path .= "$key/";

arraySearchRecursive($needle, $value, $path);

unset($path);

} else {

// if not an array

// check for match

// save path if match exists

if (preg_match("/$needle/i", $value)) {

$matches[] = array($path . "$key/", "VALUE: $value");

}

}

}

// return the list of matches to the caller

return $matches;

}

// define nested array

$data = array ("United States" => array ("Texas","Philadelphia","California" => array ("Los Angeles","San Francisco" => array("Silicon Valley"))));

// search for string "in"

// result: an array of 2 occurrences with path

print_r(arraySearchRecursive("co", $data));

?>

This listing is actually a combination of techniques discussed in the listing in “Processing Nested Arrays” and the listing in “ Searching Arrays.” Here, the

custom arraySearchRecursive() function traverses the nested array, checking each key and value for matches to the search string with the preg_match()function. Matches, if any, are placed in a separate $matches array. At each stage of recursion, the “path” to the element—the sequence of array keys leading to the element—is tracked; this path is also stored in the $matches array as an aid to identifying the matching elements post search.

An alternative way to recursively search an array is to use the RecursiveIterat orIterator and RecursiveArrayIterator objects, two of the new Iterators available

in PHP 5.0 and better. To do this, initialize a RecursiveIteratorIterator object (this is an Iterator designed solely for the purpose of iterating over other recursive

Iterators) and pass it a newly minted RecursiveArrayIterator. You can now search all the elements of the nested array(s) with a foreach() loop and a call to preg_match().

Here’s an example:

<?php

// define associative array

$data = array ("United States" => array ("Texas","Philadelphia","California" => array ("Los Angeles","San Francisco" => array("Silicon Valley"))));

// define search string

$needle = "il";

$matches = array();

// recursively search array

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));

foreach ($iterator as $value) {

if(preg_match("/$needle/i", $value)) {

$matches[] = $value;

}

}

// print matching values

// result: ("Philadelphia", "Silicon Valley")

print_r($matches);

?>

You can read more about the RecursiveArrayIterator, the RecursiveIteratorIterat or, and the RecursiveIterator interfaces at http://www.php.net/~helly/php/ext/spl/.

Filtering Array Elements

Problem

You want to eliminate those elements of an array that don’t match certain criteria.

Solution

Create a custom filter for the array with PHP’s array_filter() function:

<?php

// function to test if a number is positive

function isPositive($value) {

return ($value > 0) ? true : false;

}

// define array of numbers

$series = array(-10,21,43,-6,5,1,84,1,-32);

// filter out positive values

// result: (21, 43, 5, 1, 84, 1)

print_r(array_filter($series, 'isPositive'));

?>

PHP’s array_filter() function is great for identifying those array elements that match specific, user-defined criteria. It works by running each array member

through a user-defined function and checking the return value. Those array members associated with a true return are flagged as “special,” and placed in a separate array.

This is clearly illustrated in the previous listing. Here, the user-defined isPositive() function returns true if its input argument is greater than 0. The array_filter() function runs isPositive() on every member of the $series array, and checks to see which members generate a true value. The true return serves as a flag to filter out positive values, which are then placed in a separate $positives array.

Sorting Arrays

Problem

You want to sort an array by key or value.

Solution

Use PHP’s sort() function on numerically indexed arrays:

<?php

// define indexed array

$animals = array("wolf", "lion", "tiger", "iguana", "bear","zebra", "leopard");

// sort alphabetically by value

// result: ("bear", "iguana", "leopard", "lion", "tiger", "wolf","zebra")

sort($animals);

print_r($animals);

?>

Use PHP’s asort() or ksort() function on string-indexed arrays:

<?php

// define associative array

$animals = array("wolf" => "Rex", "tiger" => "William","bear" => "Leo", "zebra" => "Adam", "leopard" => "Ian");

// sort alphabetically by value, retaining keys

// result: ("zebra" => "Adam", ..., "tiger" => "William")

asort($animals);

print_r($animals);

// sort alphabetically by keys, retaining values

// result: ("bear" => "Leo", ..., "zebra" => "Adam")

ksort($animals);

print_r($animals);

?>

PHP’s array manipulation API comes with a number of functions to sort array elements. The most commonly used one is the sort() function, which sorts

Numerically indexed arrays in alphanumeric order. This function is not suitable for associative arrays, as it destroys the key-value association of those arrays. If you need to sort an associative array, consider using the asort() or ksort() functions,which sort these arrays by value and key respectively while simultaneously maintaining the key-value relationship. The previous listing illustrates all three of these functions.

An interesting entrant in the sort sweepstakes is the natsort() function, which sorts array elements using a natural-language algorithm. This comes in handy to sort array values “the way a human being would.” Key-value associations are maintained throughout the sorting process. The next listing illustrates this:

<?php

// define array

$userList = array("user1","user10","user20","user2");

// normal sort

// result: ("user1", "user10", "user2", "user20")

sort($userList);

print_r($userList);

// natural-language sort

// result: ("user1", "user2", "user10", "user20")

natsort($userList);

print_r($userList);

?>

TIP:

You can reverse the sort order of the sort(), asort(), and ksort() functions by replacing them with calls to rsort(), arsort(), and krsort() respectively.

Sorting Multidimensional Arrays

Problem

You want to sort a multidimensional array using multiple keys.

Solution

Use PHP’s array_multisort() function:

<?php

// create a multidimensional array

$data = array();

$data[0] = array("title" => "Net Force", "author" => "Clancy, Tom","rating" => 4);

$data[1] = array("title" => "Every Dead Thing", "author" => "Connolly,John", "rating"=> 5);

$data[2] = array("title" => "Driven To Extremes", "author" => "Allen,James", "rating" => 4);

$data[3] = array("title" => "Dark Hollow", "author" => "Connolly,John", "rating" => 4);

$data[4] = array("title" => "Bombay Ice", "author" => "Forbes,Leslie", "rating" => 5);

// separate all the elements with the same key

// into individual arrays

foreach ($data as $key=>$value) {

$author[$key] = $value['author'];

$title[$key] = $value['title'];

$rating[$key] = $value['rating'];

}

// sort by rating and then author

array_multisort($rating, $author, $data);

print_r($data);

?>

If you’re familiar with Structured Query Language (SQL), you already know how the ORDER BY clause enables you to sort a resultset by more than one field. That’s essentially what the array_multisort() function was designed to do: it accepts a series of input arrays and uses them as sort criteria. Sorting begins with the first array; values in that array that evaluate as equal are sorted by the next array, and so on.

This function comes in handy when dealing with symmetrical multidimensional arrays, like the one in the previous listing. Such an array is typically created from an SQL resultset. To sort such an array, first break it into individual single arrays, one for each unique key, and then use array_multisort() to sort the arrays in the priority you desire. In such a situation, the last argument to array_multisort()must be the original multidimensional array.

Sorting Arrays Using a Custom Sort Function

Problem

You want to sort an array using a custom sorting algorithm.

Solution

Define your sorting algorithm and use the usort() function to process an array with it:

<?php

// function to compare length of two values

function sortByLength($a, $b) {

if (is_scalar($a) && is_scalar($b)) {

if (strlen($a) == strlen($b)) {

return 0;

} else {

return (strlen($a) > strlen($b)) ? 1 : -1;

}

}

}

// define array

$data = array("abracadabra", "goo", "indefinitely","hail to the chief", "aloha");

// sort array using custom sorting function

// result: ("goo", "aloha", ..., "hail to the chief")

usort($data, 'sortByLength');

print_r($data);

?>

Often, PHP’s built-in sorting functions may be insufficient for your needs. For such situations, PHP offers the usort() function, which enables you to sort an array using a custom sorting algorithm. This sorting algorithm is nothing more than a comparison function, which accepts two arguments and decides whether one is larger or smaller than the other. The comparison must return a number less than 0 if the first argument is to be considered less than the second, and a number greater than 0 if the first argument is to be considered greater than the second. The previous listing illustrates this, presenting a comparison function that can

be used to sort array elements by their length, with the shortest items first. The strlen() function is used to calculate the number of characters in each element;

This then serves as the basis for re-sorting the array.

Sorting Nested Arrays

Problem

You want to sort a series of nested arrays.

Solution

Write a recursive function to traverse the arrays and sort each one:

<?php

// function to compare length of two values

function sortByLength($a, $b) {

if (is_scalar($a) && is_scalar($b)) {

if (strlen($a) == strlen($b)) {

return 0;

} else {

return (strlen($a) > strlen($b)) ? 1 : -1;

}

}

}

// function to recursively sort

// a series of nested arrays

function sortRecursive(&$arr, $sortFunc, $sortFuncParams = null) {

// check if input is array

if (!is_array($arr)) { die ("Argument is not array!"); }

// sort the array using the named function

$sortFunc($arr, $sortFuncParams);

// check to see if further arrays exist

// recurse if so

foreach (array_keys($arr) as $k) {

if (is_array($arr[$k])) {

sortRecursive($arr[$k], $sortFunc, $sortFuncParams);

}

}

}

// define nested array

$data = array (

"United States" => array (

"West Virginia",

"Texas" => array(

"Dallas", "Austin"),

"Philadelphia", "Vermont", "Kentucky",

"California" => array (

"San Francisco", "Los Angeles", "Cupertino", "Mountain View")));

// sort $data recursively using asort()

sortRecursive($data, 'asort');

print_r($data);

// sort $data recursively using custom function()

sortRecursive($data, 'usort', 'sortByLength');

print_r($data);

?>

This listing builds on the technique discussed in the listing in “4.3: Processing Nested Arrays” to recursively traverse a series of nested arrays. The sortRecursive()function accepts three arguments: an array, the name of an array sorting function (either built-in or user-defined), and optional arguments to said function. It then traverses the array and all the arrays internal to it, sorting each by the specified function.

Note that the array input to sortRecursive() is passed by reference, so any changes take place to the array variable itself and not a copy.

Merging Arrays

Problem

You want to merge two or more arrays into a single array.

Solution

Use PHP’s array_merge() or array_merge_recursive() functions:

<?php

// define arrays

$statesUS = array("Maine", "New York", "Florida", "California");

$statesIN = array("Maharashtra", "Tamil Nadu", "Kerala");

// merge into a single array

// result: ("Maine", "New York", ..., "Tamil Nadu", "Kerala")

$states = array_merge($statesUS, $statesIN);

print_r($states);

?>

<?php

// define arrays

$ab = array("a" => "apple", "b" => "baby");

$ac = array("a" => "anteater", "c" => "cauliflower");

$bcd = array("b" => "ball", "c" => array("car", "caterpillar"),"d" => "demon");

// recursively merge into a single array

$abcd = array_merge_recursive($ab, $ac, $bcd);

print_r($abcd);

?>

PHP’s array_merge() function accepts two or more arrays as arguments, and combines them to create a single array. The behavior of this function is fairly

straightforward when dealing with numerically indexed arrays, but can trip you up when you’re working with associative arrays: If you try merging associative arrays that have some key names in common, only the last such key-value pair will appear in the merged array.

To work around this problem, use the array_merge_recursive() function when merging associative arrays. This function ensures that common keys are

recursively merged into a single sub-array and no data is lost during the merge process. You see this in the output of the second listing in the previous code.

You can also create an associative array by merging two numerically indexed arrays, using the array_combine() function. Elements of the first array are

converted into keys of the combined array, while elements of the second array become the corresponding values. Here’s an example:

<?php

// define array for keys

$keys = array("UK", "US", "FR", "IN");

// define array for values

$values = array("London", "Washington", "Paris", "Delhi");

// combine into single associative array

// returns ("UK" => "London", "US" => "Washington", ...)

$capitals = array_combine($keys, $values)or die ("Unable to match keys and values");

print_r($capitals);

?>

Comparing Arrays

Problem

You want to compare two arrays to find the common or different elements.

Solution

Use PHP’s array_intersect() function to find the elements common to two arrays:

<?php

// define arrays

$salt = array("sodium", "chlorine");

$acid = array("hydrogen", "chlorine", "nitrogen");

// get all elements from $acid

// that also exist in $salt

// result: ("chlorine")

$intersection = array_intersect($acid, $salt);

print_r($intersection);

?>

Use PHP’s array_diff() function to find the elements that exist in either one of the two arrays, but not both simultaneously:

<?php

// define arrays

$salt = array("sodium", "chlorine");

$acid = array("hydrogen", "chlorine", "nitrogen");

// get all elements that do not exist

// in both arrays simultaneously

// result: ("hydrogen", "nitrogen", "sodium")

$diff = array_unique(array_merge(array_diff($acid, $salt), array_diff($salt, $acid)));

print_r($diff);

?>

venn diagram using php array

Consider a Venn diagram illustrating the intersection of two sets.Assuming these sets are represented as arrays, most developers find themselves

having to deal with one of two tasks: finding the elements common to both arrays (C), or finding the elements that exist in either one of the two arrays, but not both simultaneously (A+B).

Obtaining the common set elements (C) is simple—the array_intersect()function is designed to do just this. Finding the elements that exist in either one of

the two arrays, but not both simultaneously, is a little more complex, and requires knowledge of the array_diff() function.

Given two arrays, this array_diff() function returns all the elements from the second array that do not exist in the first. This means that you can obtain the required (A+B) set by running array_diff() twice, swapping the order of comparison each time, and then merging the resulting arrays. You should also run the array_unique() function on the merged array to eliminate any duplicates. This process is illustrated in the second listing.

Note that the array_diff() and array_intersect() functions only compare array values; they ignore the corresponding keys when calculating the

array intersection or difference. You can improve on this situation by providing the array_diff_assoc() and array_intersect_assoc() functions, which take keys into account as well. The following listing illustrates the difference:

</pre>
<?php

// define arrays

$a = array("sodium", "chlorine", "hydrogen");

$b = array("chlorine", "sodium", "hydrogen");

// insensitive to keys

// result: ()

print_r(array_diff($a, $b));

// sensitive to keys

// result: ("sodium", "chlorine")

print_r(array_diff_assoc($a, $b));

// insensitive to keys

// result: ("sodium", "chlorine", "hydrogen")

print_r(array_intersect($a, $b));

// sensitive to keys

// result: ("hydrogen")

print_r(array_intersect_assoc($a, $b));

?>

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I graduated in 2009 with a bachelor's degree in Engineering from State University Of Bangladesh, I'm also a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, CIDA and MAX Group where I worked on ERP software and web development., but now i'm a co-founder and Chief Executive Officer and Managing Director of TechBeeo Software Consultancy Services Ltd. I'm also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute - a leading Training Institute in the country.
2 comments on “Working With PHP Arrays

Leave a Reply

Your email address will not be published. Required fields are marked *