PHP Arrays PHP

The functions in this section operate on arrays. Some of them sort the arrays; some of them help you find and retrieve values from arrays

array array(...)
The array function takes a list of values separated by commas and returns an array. This is especially useful for creating one-off arrays to be passed to functions. Elements will beadded to the array as if you used empty square brackets, which means they are numbered consecutively starting at zero. You may use the => operator to specify index values.

<?
//create an array
$myArray = array(
"Name"=>"Leon Atkinson",
"Profession"=>array("Programmer", "Author"),
"Residence"=>"Martinez, California"
);
?>

array array_count_values(array data)
The array_count_values function returns counts for each distinct value in the data argument. The returned array is indexed by the values of the data argument. Although the example below uses an array of numbers, array_count_values will count the appearance of elements that contain any other data type.

array_count_values

array_count_values

array_count_values

array array_keys(array data, string value)
The array_keys function returns an array of the keys used in the data array. If the optional value argument is supplied, only the subset of indices that point the given element value are returned.

array array_keys(array data, string value)

<?
//create random test data with 0 or 1
Core PHP Programming
IT-SC book 224
srand(time());
for($i=0; $i<10; $i++)
{
$data[] = rand(0,1);
}
//print out the keys to 1's
foreach(array_keys($data, 1) as $key)
{
print("$key<BR>n");
}
?>

array array_merge (array data, array data, ...)
The array_merge function takes two or more arrays and returns a single array containing all elements. Elements indexed by integers are added to the new array one at a time, in most cases renumbering them. Elements indexed by strings retain their index values and are added as they are encountered in the input arrays. They may replace previous values. If you are unsure of the indices used in the merged arrays, you can use array_values to make sure all values are indexed by an integer.

<?
function printElement($element)
{
print("$element<BR>n");
}
//set up an array of color names
$colors = array("red", "blue", "green");
$more_colors = array("yellow", "purple", "orange");
//merge arrays
$all_colors = array_merge($colors, $more_colors);
//print out all the values
array_walk($all_colors, "printElement");
?>

boolean array_multisort(array data, integer direction, ...)
The array_multisort function sorts arrays together, as if array were a column in a table. The data argument is an array and the direction argument is one of twoconstants: SORT_ASC or SORT_DESC. These stand for ascending and descending, respectively. If left out, the direction defaults to ascending order, which is smallest to largest. You may specify any number of arrays, but you must alternate between arrays and sort order constants as you do.

array_multisort

array_multisort

array_multisort

The way array_multisort works is similar to the way a relational database sorts the results of a join. The first element of each array is joined into a virtual row, and all elements in a row move together. The arrays are sorted by the first array. In the case where elements of the first array repeat, rows are sorted on the second row. Sorting continues as necessary.

array array_pad(array data, integer size, value padding)
The array_pad function adds elements to an array until it has the number of elements specified by the size argument. If the array is long enough already, no elements are added. Otherwise, the padding argument is used for the value of the new elements. If the size argument is positive, padding is added to the end of the array. If the size argument is negative, padding is added to the beginning.

//create test data
$data = array(1,2,3);
//add "start" to beginning of array
$data = array_pad($data, -4, "start");
//add "end" to end of array
$data = array_pad($data, 5, "end");
foreach($data as $value)
{
print("$value<BR>n");
}
?>

value array_pop(array stack)
The array_pop function returns the last element of an array, removing it from the array as well. The array_push function compliments it, and array_shift and array_unshift add and remove elements from the beginning of an array.

<?
//set up an array of color names
$colors = array("red", "blue", "green");
$lastColor = array_pop($colors);
//prints "green"
print($lastColor . "<BR>n");
//shows that colors contains red, blue
print("<PRE>");
print_r($colors);
print("</PRE>n");
?>

boolean array_push(array stack, expression entry, ...)
The array_push function adds one or more values to the end of an array. It treats the array as a stack. Use array_pop to remove elements from the stack. The array_shift and array_unshift functions add and remove elements to the beginning of an array.

<?
//set up an array of color names
$colors = array("red", "blue", "green");
//push two more color names
array_push($colors, "purple", "yellow");
//print out all the values
//(red, blue, green, purple, yellow)
print("<PRE>");
print_r($colors);
print("</PRE>n".);
?>

array array_reverse(array data)
The array_reverse function returns the data argument with the elements in reverse order. The elements are not sorted in any way. They are simply in the opposite order.

<?
//create test data
$data = array(3, 1, 2, 7, 5);
//reverse order
$data = array_reverse($data);
//print in reverse order
//5, 7, 2, 1, 3
print("<PRE>");
print_r($data);
print("</PRE>n");
?>

value array_shift(array stack)
The array_shift function returns the first element of an array, removing it as well. This allows you to treat the array like a stack. The array_unshift function adds an element to the beginning of an array. Use array_pop and array_push to perform the same actions with the end of the array.

<?
//set up an array of color names
$colors = array("red", "blue", "green");
$firstColor = array_shift($colors);
//print "red"
print($firstColor . "<BR>n");
//dump colors (blue, green)
print("<PRE>");
print_r($colors);
print("</PRE>n");
?>

array array_slice(array data, integer start, integer stop)
The array_slice function returns part of an array, starting with the element specified by the start argument. If you specify a negative value for start, the starting position will be that many elements before the last element. The optional stop argument allows you to specify how many elements to return or where to stop returning values. A positive value is treated as a maximum number of elements to return. A negative stop is used to count backward from the last element to specify the element at which to stop.Compare this function to array_merge and array_splice.

<?
function printElement($element)
{
print("$element<BR>n");
}
//set up an array of color names
$colors = array("red", "blue", "green",
"purple", "cyan", "yellow");
//get a new array consisting of a slice
//from "green" to "cyan"
$colors_slice = array_slice($colors, 2, 3);
//print out all the values
array_walk($colors_slice, "printElement");
?>

array_splice(array data, integer start, integer stop, array insert_data)
The array_splice function removes part of an array and inserts another in its place. The array passed is altered in place, not returned. Starting with the element specified by the start argument, elements are removed until the element specified by the stop argument is reached. If stop is left out, then removal continues until the end of the array. If stop is negative, it references from the end of the array backward. It is possible to specify start and stop values that do not actually remove any values. For instance, the stop value may be positive and less than start. This is a valid way to use array_splice to insert an array without removing any elements.

In place of any removed elements, the array passed as the insert_data argument is inserted if it is supplied. Declaring it is optional, as you may wish simply to remove some elements. If you wish to insert a single element into the array, you do not need to supply an array for insert_data. Compare this function to array_merge and array_slice.

<?
function printElement($element)
{
print("$element<BR>n");
}
//set up an array of color names
$colors = array("red", "blue", "green",
"yellow", "orange", "purple");
//remove green
array_splice($colors, 2, 2);
//insert "pink" after "blue"
array_splice($colors, 2, 0, "pink");
//insert "cyan" and "black" between
//"orange" and "purple"
array_splice($colors, 4, 0, array("cyan", "black"));
//print out all the values
array_walk($colors, "printElement");
?>

boolean array_unshift(array stack, expression entry, ...)
The array_unshift function adds one or more values to the beginning of an array, as if the array were a stack. Use array_shift to remove an element from the beginning of an array. Compare this function to array_pop and array_push, which operate on the end of the array.

<?
function printElement($element)
{
print("$element<BR>n");
}
//set up an array of color names
$colors = array("red", "blue", "green");
//push two more color names
array_unshift($colors, "purple", "yellow");
//print out all the values
array_walk($colors, "printElement");
?>

array array_values(array data)
The array_values function returns just the array elements, re-indexed with integers.

<?
//set up an array of color names
$UserInfo = array("First Name"=>"Leon",
"Last Name"=>"Atkinson",
"Favorite Language"=>"PHP");
//re-index using integers
$UserInfo = array_values($UserInfo);
//print out all the values and their
//new indices
for($n=0; $n count($UserInfo); $n++)
{
print("($n) $UserInfo[$n]<BR>n");
}
?>

boolean array_walk(array data, string function)
The array_walk function executes the specified function on each element of the given array. The function must take exactly one element; otherwise an error message is generated. The array elements will be passed by reference, so any change made to them by the specified function will be permanent in the array. The function specified must be one you create, not a built-in PHP function.

<?
$colors = array("red", "blue", "green");
function printElement($element)
{
print("$element<BR>n");
}
array_walk($colors, "printElement");
?>

arsort(array unsorted_array)
The arsort function sorts an array in reverse order by its values. The indices are moved along with the values. This sort is intended for associative arrays.

<?
// build array
$users = array("bob"=>"Robert",
"steve"=>"Stephen",
"jon"=>"Jonathon");
// sort array
arsort($users);
// print out the values
for(reset($users); $index=key($users); next($users))
{
print("$index : $users[$index] <BR>n");
}
?>

asort(array unsorted_array)
The asort function sorts an array by its values. The indices are moved along with the values. This sort is intended for associative arrays.

<?
// build array
$users = array("bob"=>"Robert",
"steve"=>"Stephen",
"jon"=>"Jonathon");
// sort array
asort($users);
// print out the values
for(reset($users); $index=key($users); next($users))
{
print("$index : $users[$index] <BR>n");
}
?>

array compact(...)
The compact function returns an array containing the names and values of variables named by the arguments. Any number of arguments may be passed, and they may be single string values or arrays of string values. Arrays containing other arrays will be recursively explored. The variables must be in the current scope. This function complements extract, which creates variables from an array.

compact

compact

compact

The count function returns the number of elements in an array. If the variable has never been set, count returns zero. If the variable is not an array, count returns 1. Despite this added functionality, you should use the isset and is_array functions to determine the nature of a variable.

<?
$colors = array("red", "green", "blue");
print(count($colors));
?>

integer count(variable array)
The count function returns the number of elements in an array. If the variable has neverbeen set, count returns zero. If the variable is not an array, count returns 1. Despite thisadded functionality, you should use the isset and is_array functions to determine the
nature of a variable.

<?
$colors = array("red", "green", "blue");
print(count($colors));
?>

value current(array arrayname)
The current function returns the value of the current element pointed to by PHP's internal pointer. Each array maintains a pointer to one of the elements of an array. Bydefault it points to the first element added to the array until it is moved by a function such as next or reset.

<?
//create test data
$colors = array("red", "green", "blue");
//loop through array using current
for(reset($colors); $value = current($colors); next($colors))
{
print("$value<BR>n");
}
?>

array each(array arrayname)
The each function returns a four-element array that represents the next value from an array. The four elements of the returned array (0, 1, key, and value) refer to the key and value of the current element. You may refer to the key with 0 or key, and to get the value use 1 or value. You may traverse an entire array by repeatedly using list and each, as in the example below.

<?
//create test data
$colors = array("red", "green", "blue");
//loop through array using each
//output will be like "0 = red"
while(list($key, $value) = each($colors))
{
print("$key = $value<BR>n");
}
?>

end(array arrayname)
The end function moves PHP's internal array pointer to the array's last element. The reset function moves the internal pointer to the first element.

<?
$colors = array("red", "green", "blue");
end($colors);
print(current($colors));
?>

array explode(string delimiter, string data)
The explode function creates an array from a string. The delimiter argument divides the data argument into elements. This function is safe for use with binary strings. The implode function will convert an array into a string.

<?
/*
** convert tab-delimited list into an array
*/
$data = "redtgreentblue";
$colors = explode("t", $data);
// print out the values
for($index=0; $index < count($colors); $index++)
{
print("$index : $colors[$index] <BR>n");
}
?>

extract(array variables, integer mode, string prefix)
The extract function creates variables in the local scope based on elements in the variables argument. Elements not indexed by strings are ignored. The optional mode argument controls whether variables overwrite existing variables or are renamed to avoid a collision. The valid modes are listed. If left out, EXTR_OVERWRITE mode is assumed. The prefix argument is required only if EXTR_PREFIX_SAME or EXTR_PREFIX_ALL modes are chosen. If used, the prefix argument and an underscore are added to the name of the extracted variable. Compare this function to compact, which creates an array based on variables in the local scope.

<?
$new_variables = array('Name'=>'Leon', 'Language'=>'PHP');
$Language = 'English';
extract($new_variables, EXTR_PREFIX_SAME, "collision");
//print extracted variables
print($Name . "<BR>n");
print($collision_Language . "<BR>n");
?>

boolean in_array(value query, array data)
The in_array function returns TRUE if the query argument is an element of the dataargument.

extract-Modes

//create test data
$colors = array("red", "green", "blue");
//test for the presence of green
if(in_array("green", $colors))
{
print("Yes, green is present!");
}
?>

string implode(array data, string delimiter)
The implode function transforms an array into a string .The elements are concatenated with the delimiter string separating them. To perform the reverse functionality, use explode.

<?
/*
** convert an array into a comma-delimited string
*/
$colors = array("red", "green", "blue");
$colors = implode($colors, ",");
print($colors);
?>

join
You may use join as an alias to the implode function.

value key(array arrayname)
The key function returns the index of the current element. Use current to find the value of the current element.

<?
$colors = array("FF0000"=>"red",
"00FF00"=>"green",
"0000FF"=>"blue");
for(reset($colors); $key = key($colors); next($colors))
{
print("$key is $colors[$key]<BR>n");
}
?>

boolean krsort(array data)
The krsort function sorts an array by its keys in reverse order—that is, largest values first. The element values are moved along with the keys. This is mainly for the benefit of associative arrays, since arrays indexed by integers can easily be traversed in order of their keys.

<?
$colors = array("red"=>"FF0000",
"green"=>"00FF00",
"blue"=>"0000FF");
// sort an array by its keys
krsort($colors);
// print out the values
foreach($colors as $key=>$value)
{
print("$key : $value <BR>n");
}
?>

boolean ksort(array data)
The ksort function sorts an array by its keys, or index values. The element values are moved along with the keys. This is mainly for the benefit of associative arrays, since arrays indexed by integers can easily be traversed in order of their keys.

<?
$colors = array("red"=>"FF0000",
"green"=>"00FF00",
"blue"=>"0000FF");
// sort an array by its keys
ksort($colors);
// print out the values
foreach($colors as $key=>$value)
{
print("$key : $value <BR>n");
}
?>

list(...)
The list function treats a list of variables as if they were an array. It may only be used on the left side of an assignment operator. It is useful for translating a returned array directly into a set of variables.

<?
$colors = array("red", "green", "blue");
//put first two elements of returned array
//into key and value, respectively
list($key, $value) = each($colors);
print("$key: $value<BR>n");
?>

value max(array arrayname) value max(...)
The max function returns the largest value from all the array elements. If all values are strings, then the values will be compared as strings. If any of the values is a number, only the integers and doubles will be compared numerically. The alternate version of the max function takes any number of arguments and returns the largest of them. With this use, you must supply at least two values.
To find the minimum value, use min.

<?
$colors = array("red"=>"FF0000",
"green"=>"00FF00",
"blue"=>"0000FF");
//prints FF0000
print(max($colors) . "<BR>n");
//prints 13
print(max("hello", "55", 13) . "<BR>n");
//prints 17
print(max(1, 17, 3, 5.5) . "<BR>n");
?>

value min(array arrayname) value min(...)
The min function returns the smallest value from all the array elements. If all values are strings, then the values will be compared as strings. If any of the values is a number, only the integers and doubles will be compared numerically. The alternate version of the min function takes any number of arguments and returns the smallest of them. You must
supply at least two values.

<?
$colors = array("red"=>"FF0000",
"green"=>"00FF00",
"blue"=>"0000FF");
//prints 0000FF
print(min($colors) . "<BR>n");
//prints 13
print(min("hello", "55", 13) . "<BR>n");
//prints 1
print(min(1, 17, 3, 5.5) . "<BR>n");
?>

value next(array arrayname)
The next function moves PHP's array pointer forward one element. It returns the value at the new element. If the pointer is already at the end of the array, FALSE is returned.

<?
$colors = array("red", "green", "blue");
$my_color = current($colors);
do
{
print("$my_color <BR>n");
}
while($my_color = next($colors))
?>

pos
You may use pos as an alias to the current function.

value prev(array arrayname)
The prev function operates similarly to the next function with the exception that it moves backward through the array. The internal pointer to the array is moved back one element, and the value at that position is returned. If the pointer is already at the beginning, FALSE is returned.

<?
$colors = array("red", "green", "blue");
end($colors);
$my_color = current($colors);
do
{
print("$my_color <BR>n");
}
while($my_color = prev($colors))
?>

array range(integer start, integer stop)
Use range to create an array containing every integer between the first argument and the second, inclusive.

<?
$numbers = range(13, 19);
//print out all the values
foreach($numbers as $value)
{
print("$value<BR>n");
}
?>

value reset(array arrayname)
Use the reset function to move an array's internal pointer to the first element. The element in the first position is returned. Use end to set the pointer to the last element.

<?
//create test data
$colors = array("red", "green", "blue");
//move internal pointer
next($colors);
//set internal pointer to first element
reset($colors);
//show which element we're at (red)
print(current($colors));
?>

rsort(array unsorted_array)
The rsort function sorts an array in reverse order. As with other sorting functions, the presence of string values will cause all values to be treated as strings and the elements will be sorted alphabetically. If all the elements are numbers, they will be sorted numerically. The difference between rsort and arsort is that rsort discards any key values and reassigns elements with key values starting at zero.

<?
//create test data
$colors = array("one"=>"orange", "two"=>"cyan",
"three"=>"purple");
//sort and discard keys
rsort($colors);
//show array
foreach($colors as $key=>$value)
{
print("$key = $value<BR>n");
}
?>

shuffle(array data)
The shuffle function randomly rearranges the elements in an array. The srand function may be used to seed the random number generator, but as with the rand function, a seed based on the current time will be used if you do not provide a seed.

<?
//create test data
$numbers = range(1, 10);
//rearrange
shuffle($numbers);
//print out all the values
foreach($numbers as $value)
{
print("$value<BR>n");
}
?>

sizeof
This is an alias for the count function.

sort(array unsorted_array)
The sort function sorts an array by element values from lowest to highest. If any element is a string, all elements will be converted to strings for the purpose of comparison, which will be made alphabetically. If all elements are numbers, they will be sorted numerically. Like rsort, sort discards key values and reassigns elements with key values starting at zero.

<?
//create test data
$colors = array("one"=>"orange", "two"=>"cyan",
"three"=>"purple");
//sort and discard keys
sort($colors);
//show array
foreach($colors as $key=>$value)
{
print("$key = $value<BR>n");
}
?>

uasort(array unsorted_array, string comparison_function)
The uasort function sorts an array using a custom comparison function. The index values, or keys, move along with the element values, similar to the behavior of the assort function.

The comparison function must return a signed integer. If it returns zero, then two elements are considered equal. If a negative number is returned, the two elements are considered to be in order. If a positive number is returned, the two elements are considered to be out of order.

<?
/*
** duplicate normal ordering
*/
function compare($left, $right)
{
return($left - $right);
}
//create test data
$some_numbers = array(
"red"=>6,
"green"=>4,
"blue"=>8,
"yellow"=>2,
"orange"=>7,
"cyan"=>1,
"purple"=>9,
"magenta"=>3,
"black"=>5);
//sort using custom compare
uasort($some_numbers, "compare");
//show sorted array
foreach($some_numbers as $key=>$value)
{
print($key . "=" . $value . "<BR>n");
}
?>

uksort(array unsorted_array, string comparison_function)
The uksort function sorts an array using a custom comparison function. Unlike usort, the array will be sorted by the index values, not the elements. The comparison function must return a signed integer. If it returns zero, then two indices are considered equal. If a negative number is returned, the two indices are considered to be in order. If a positive number is returned, the two indices are considered to be out of order.

<?
/*
** duplicate normal ordering
*/
function compare($left, $right)
{
return($left - $right);
}
//create test data
srand(time());
for($i=0; $i<10; $i++)
{
$data[rand(1,100)] = rand(1,100);
}
//sort using custom compare
uksort($data, "compare");
//show sorted array
foreach($data as $key=>$value)
{
print($key . "=" . $value . "<BR>n");
}
?>

usort(array unsorted_array, string compare_function)
The usort function sorts an array by element values using a custom comparison function. The function must return a signed integer. If it returns zero, then two elements are considered equal.If a negative number is returned, the two elements are considered to be in order. If a positive number is returned, the two elements are considered to be out of order.

<?
/*
** duplicate normal ordering
*/
function compare($left, $right)
{
return($left - $right);
}
//create test data
srand(time());
for($i=0; $i<10; $i++)
{
$data[rand(1,100)] = rand(1,100);
}
//sort using custom compare
usort($data, "compare");
//show sorted array
foreach($data as $key=>$value)
{
print($key . "=" . $value . "<BR>n");
}
?>

Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

PHP Topics