Home arrow PHP arrow Page 3 - PHP Array Function Tutorial

PHP asort, array_pop, array_merge, and array_search Functions - PHP

PHP array string functions are some of the most important functions you need to know in PHP if you want to become an efficient programmer. In this tutorial, we will look at the most commonly used array string functions, including (but not limited to) count, push, in_array, asort, and pop.

TABLE OF CONTENTS:
  1. PHP Array Function Tutorial
  2. Common Array String Functions
  3. PHP asort, array_pop, array_merge, and array_search Functions
By: Codex-M
Rating: starstarstarstarstar / 3
May 11, 2011

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

5.) array_values() = this will be used to reset any gaps in the indexes caused after implementation of array_unique. In the previous example, you will notice that the indexes are 0,1,2 and 4 (3 is removed because it is a duplicate). You can reset it back to 0,1,2,3,4 using array_values() function:

<?php
$fivecolors=array("blue","red","yellow","red","magenta");
$unique=array_unique($fivecolors);
//reset the numbering of index to the correct sequence, removing any gaps
$resettedindex= array_values($unique);
//output to browser
var_dump($resettedindex);
?>

The following is the output:

array(4) {
[0]=> string(4) "blue"
[1]=> string(3) "red"
[2]=> string(6) "yellow"
[3]=> string(7) "magenta"
}

The key indexes are now in the correct sequence (0,1,2,3).

6.) array_change_key_case() = this function can be used to produce a uniform casing in all strings present in the array. Sometimes you will be processing string elements in an array that does not have uniform casing distribution (for example, strings with both upper and lowercases). If you need to make all casing “upper case” or “lower case”; then you can use this function.

Example:

<?php
$mixedcase=array("bLuE"=>1,"RED"=>2,"Yellow"=>3,"mAgENTA"=>4); //convert all strings in the array to UPPER CASE $uppercase= array_change_key_case($mixedcase, CASE_UPPER); //dump the array var_dump($uppercase); ?>

This is the output:

array(4) {
["BLUE"]=>int(1) ["RED"]=>int(2) ["YELLOW"]=>int(3) ["MAGENTA"]=>int(4) }

Note: If you do not specify CASE_UPPER, the default is lowercase.

7.) array_count_values = this will return the frequency of occurrences of elements in an array. Example:

<?php
$fivecolors=array("blue","red","yellow","red","magenta");
//return the frequency of occurrences
$frequency=array_count_values($fivecolors);
var_dump($frequency);
?>

This will return the following result:

array(4) {
["blue"]=>int(1)
["red"]=>int(2)
["yellow"]=>int(1)
["magenta"]=>int(1)
}

You may have noticed that the var_dump result is an associative array. To extract the specific frequency of occurrence - for example the red color:

<?php
$fivecolors=array("blue","red","yellow","red","magenta");
$frequency=array_count_values($fivecolors);
//return the frequency of occurrence for red color only
echo $frequency["red"];
?>

8.) array_search = this will search the given string in the array variable and return it if the index key number is found. Example:

<?php
$fivecolors=array("blue","red","yellow","magenta");
//Search the color blue and return the key
$key = array_search('blue', $fivecolors);
echo $key;
?>

The result is 0 because blue is the first element in the array. Another example:

<?php
$fivecolors=array("blue","red","yellow","magenta");
//Search the color white and return the key
$key = array_search('white', $fivecolors);
echo $key;
?>

The result is False/Null or 0 logic because white color is not included in the array. Bear in mind that 0 can be a result of two possible scenarios; the first one is that it did exist in the array and found on the first element. The second scenario is when array_search failed to find the string in the array, which in some logic can be evaluated to 0/False or null. To avoid this type of problem, you might need to test first if the string really did exist in the array by using an in_array() function.

<?php
$fivecolors=array("blue","red","yellow","red","magenta");
//Search the color white and return the key
//Check first if white color is indeed present in the array
if (in_array("white",$fivecolors)) {
//white is present in the array, now extract the key
$key = array_search('white', $fivecolors);
echo $key;
} else {
//white is not present in the array.
echo "The key does not exist for this color";
}
?>

9.) asort = this will sort the string elements found in the array variable alphabetically and maintain the corresponding index.

Example of array string elements not being sorted:

<?php
$favoritebands=array("Mary"=>"Nirvana","John" =>"Metallica","Paul"=>"Beatles","Peter"=>"Who","Alice"=>"Greenday","Chris"=>"Black Sabbath");
foreach ($favoritebands as $key => $val) {
echo "$key = $val<br />";
}
?>

This is the result (not sorted):

Mary = Nirvana
John = Metallica
Paul = Beatles
Peter = Who
Alice = Greenday
Chris = Black Sabbath

Supposing you will sort the array elements in terms of favorite band names:

<?php
$favoritebands=array("Mary"=>"Nirvana","John" =>"Metallica","Paul"=>"Beatles","Peter"=>"Who","Alice"=>"Greenday","Chris"=>"Black Sabbath");
//sort the string elements in the array while maintaining index association
asort($favoritebands);
foreach ($favoritebands as $key => $val) {
echo "$key = $val<br />";
}
?>

This is now the sorted result:

Paul = Beatles
Chris = Black Sabbath
Alice = Greenday
John = Metallica
Mary = Nirvana
Peter = Who

10.) array_merge = combines the elements of two or more arrays. Example:

<?php
$fivecolors=array("blue","red","yellow","magenta");
$threecolors=array("white","black","green");
//Merge the above two arrays
$eightcolors=array_merge($fivecolors,$threecolors);
var_dump($eightcolors);
?>

Result:

array(7) {
[0]=>string(4) "blue"
[1]=>string(3) "red"
[2]=>string(6) "yellow"
[3]=>string(7) "magenta"
[4]=>string(5) "white"
[5]=>string(5) "black"
[6]=>string(5) "green"
}

11.) array_pop = pop out the last element in the array. This is useful if you need to remove the last element when updating an array. Example:

<?php
$animals=array("bear","lion","cheetah","tiger","wolf");
//pop out last element
$pop_out = array_pop($animals);
//show pop off element
var_dump($pop_out);
//output updated animals array
var_dump($animals);
?>

Output for popping out the last element:

string(4) "wolf"

Output for updated animals array (the wolf is gone because its pop off from the array):

array(4) {
[0]=>string(4) "bear"
[1]=>string(4) "lion"
[2]=>string(7) "cheetah"
[3]=>string(5) "tiger"
}


 
 
>>> More PHP Articles          >>> More By Codex-M
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: