ON ARRAYS
|
|
Very brief introduction
|
All you need to understand this file is a basic knowledge of what functions are. Of course, if you are not interested in PHP, a widely used and beautiful server side language, this file might be of no immediate interest for you. But if you have an interest in Php I assume that you know what the arguments passed to a function are, and what its returned value is.
As for the rest, all you have to keep in mind is that in programming languages we distinguish between
- ARRAYS, which are collections of data chained together in a string whose each item can be accessed through a number, from zero onward. As such, Arrays are always ordered following the numerical sequence:
anArray[0]="whatever";
anArray[1]="whatever";
... anArray[200]="whatever";
- ASSOCIATIVE ARRAYS, which are arrays as above but this time indexed no longer by a number but by anything else, more traditionally a string of text. As such they do not have any default order, not even alphabetical: they just subsist as chains of data whose each item can be accessed by addressing its key text:
associativeArray["aKeyText"]="whatever"
What makes an array an associative array is, consequently, the presence in its chain of at least one entry whose index is not a number: that would suffice.
Also, keep in mind the distinction that affects all arrays between:
- KEY, which is the index in within the square brackets thorough which you can address single instances of the array.
- VALUE, which isn't but the actual data linked to the given key index.
Of course, remember that unlike javaScript, all variables names in PHP start with a dollar sign (foo), whereas the built in methods must be written as mere barewords.
PHP ARRAY FUNCTIONS
|
|
PHP Built in Array management functions
|
 |
 |
is_array |
 |
 commonly used |
ARGUMENTS |
RETURNS |
is_array( argument ) |
boolean |
 |
USAGE |
 |
Simple built in method to assess whether the passed argument you're dealing with is an Array or not. |
 |
 |
in_array |
 |
 commonly used |
ARGUMENTS |
RETURNS |
in_array( element, array ) |
boolean |
 |
USAGE |
 |
Simple built in method to assess whether the first passed argument is inside the Array passed as second argument - that is, if the element is among the array's values or not. |
 |
 |
isset |
 |
 commonly used |
ARGUMENTS |
RETURNS |
isset( argument ) |
boolean |
 |
USAGE |
 |
This method is not used only in Arrays but also to verify the existence of any type of variable. More specifically, it doesn't check the mere existence of a variable, it checks if such variable has ever been assigned a value. Namely if a variable has never been assigned a value, isset returns false also if the variable has been written somewhere. Conversely if a value has been assigned (even boolean false!) isset returns true:
$var1;
$var2="hallo";
$var3=0;
isset($var1); //returns false
isset($var2); //returns true
isset($var3); //returns true
Upon printing the returned values of isset, you may notice that number 1 is returned instead than true and 0 instead than false: rest assured anyway that a conditional expression checking whether the returned value is either 1 or true in case it is true, or checking whether the returned result is zero or false in case it is false, would work both ways and anyway:
if(isset($var1)==false){print "false"};
would work as well as:
if(isset($var1)==0){print "false"};
An exception: if a variable has been assigned as a value null, then isset returns false.
In order to check from within the scope of a function whether a variable initialized outside the function's scope is set, you have to resort to the built in PHP collection (array, that is) named .
It must be written with the dollar ($) sign and I do strongly recommend to write it always uppercase: since it is an array it must be followed by a set of square brackets carrying within the name of the variable (this time without the dollar sign); such variable name should go in between quotes, although PHP is smart enough to understand it is meant as a string also if you omit them:
$outside=1;
function testit(){
print (isset(["outside"]))?1:0;
}
testit();
|
 |
 |
unset |
 |
 commonly used |
ARGUMENTS |
RETURNS |
unset( argument ) |
nothing |
 |
USAGE |
 |
This method is not used only in Arrays but also to destroy any type of variable (that is, it completely frees the allocated memory for any unset variable): so it can be used to delete an entry of an array as well - or the whole array for that matter.
If you have an array of three entries such as:
$array[0]=0;
$array[1]=1;
$array[2]=2;
and then you unset for instance entry 1:
unset($array[1]);
Then the array length shrinks to two, and if iterated the loop will not pick any longer anything in position of index 1, not even NULL; but be warned that all the keys that didn't get unset are still accessible through their original indexes: that is, having deleted entry [1] doesn't mean that now entry[2] shifts of one position and has to be accessed through key 1: its key is still 2.
Unsetting a variable that has never been set and defined yields no error.
|
 |
 |
sizeof & count |
 |
 commonly used |
ARGUMENTS |
RETURNS |
sizeof( array ) count( array ) |
number |
 |
USAGE |
 |
Both functions return the amount of items in an Array (array items that hold no value whatsoever are never counted in).
count is slightly more complex insomuch as it does also the following:
- if the passed argument is a variable never set, returns zero.
- if the passed argument exists but it is not an array, returns 1
The utility of this useless behaviour is beyond my comprehension. I suggest using sizeof to count entries in an array, and in order to verify whether an array exists as a variable (that is, if it has been ever defined) use isset.
|
 |
 |
array_count_values |
 |
 used |
ARGUMENTS |
RETURNS |
array_count_values( array ) |
array |
 |
USAGE |
 |
This function, whose name is just array_count_values regardless of the fact it could be meant but for arrays, has the following purpose: counting how many times a give value is present within the values of the input array argument.
The returned output is an associative array, whose each index is one of the values found in the input array, and each of such indexes holds as its own value a number representing how many times such value now used as a key index in the returned output was present in the input array.
$array[0]=5;
$array[1]=144; $array[2]=144; $array[3]=144;
$array[4]=5;
$output=array_count_values($array)
//the returned output is:
$output[144]=3;
$output[5]=2;
The length size of the output array in our example is 2.
The only setback of it is that it tells nothing about the possible index positions of these values in the input array. A more powerful function that did that too in javascript, namely that counted all the recurrences of the values and also kept track of their positions in the original input array, is a function I scripted and called hasher. Here is a PHP implementation of that very same function, but for its documentation you should consult the documentation of its javascript version for nothing changes as far as concepts are concerned:
An ideal way to invoke it in PHP is:
$output = hasher($yourArray);
Depending upon the passed parameters what data structure is held by $output varies. Please refer once again to the javascript documentation.
|
 |
 |
foreach |
 |
 commonly used |
ARGUMENTS |
RETURNS |
foreach( $array as $key ){}
foreach( $array as $key=>$value){} |
nothing |
 |
USAGE |
 |
foreach is the most widely used loop to cycle through an array in Php. Since the other two main loops, namely for and while in php affect what is called the pointer of the array, before both for and while loops you'd make a call to reset($array), a built in php function that resets the pointer of an array to its head, whereas conversely by using foreach you have no need to reset first: foreach takes care of that by itself.
The foreach syntax is:
foreach( $array as $key){/*stuff*/}
That accesses the Array by the $key until the end is reached: $array[$key] accesses the value of the currently iterated key of the given input array..
Be warned that if the array is associative, you do have to use an alternative syntax namely:
foreach($array as $key=>$value){/*stuff*/}
Only elements highlighted are keywords, namely terms like $key and $value can have other names as long as you keep in place the symbolism.
If the array is associative and you will not use the syntax above, the keys won't be accessed even if referenced unless the key is a number data type: all the rest, like string data type keys, would be skipped! Why PHP has this rigidity in this respect I don't know for sure: but I can tell you that loops that initialize their scanning variable are normally implicitly arranged by digital interpreters to set this scanning variable as a number data type: thenceforth if it meets a key which is not a number (which is the norm in associative arrays for they are exactly defined like arrays indexed by something different than numbers only) it would not match and skip it. Some languages are more lenient about this: think of javaScript that always considers indexes of arrays as string data type even if they are... numbers, and consequently can scan them by its foreach equivalent which is called a for in cycle.
So for associative arrays use always the => version of foreach; it is a version that safely scans both associative and standard arrays. On the other hand, foreach is also the only type of loop that would scan and access associative arrays: while or for loops would not access all the keys.
TECHNICAL NOTE for curious guys:
Consider a PHP associative array like:
$foo=array("one"=>1, 2=>2, 3=>3, 4=>4);
It includes one string key and 3 numerical keys. See what happens if you loop it with a standard loop:
for($i=0; $i<sizeof($foo); $i++){print $foo[$i]."";}
The loop does as follows:
- enters the associative array. The scanning variable $i holds 0: it finds nothing with such index, and consequently it just prints a dash sign () as I instructed it.
- Second iteration $i is updated from zero to 1: still, it finds no such key as 1, for there is no such key indeed in the $foo array! So just prints another dash.
- Third iteration $i is updated to number 2: now it finds a key with such number, which actually was the preceding one, and prints its value which is 2 as well.
- Eventually, last iteration $i=3, and finds one entry whose key is 3.
- The output prints: - - 2- 3-
This shows to you that for and while loops actually do not iterate an array, but simply increase from zero onward the scanning variable they have initialized within themselves, and by that variable they interrogate and probe the array: there is no such thing as "unfolding the array": arrays get interrogated, not unfolded.
|
 |
 |
each |
 |
 commonly used |
ARGUMENTS |
RETURNS |
each( array ) |
array |
 |
USAGE |
 |
This method takes as its argument an array and performs the following: it reproduces an output array for the first item of the input array; this output array is composed of 2 (two) elements that have the peculiarity they can be both addressed in two ways:
- The first element can be addressed as:
- number 0: the key of an entry of the input array
- string "key": still the key of an entry of the input array, now retrievable by a string index instead than by number zero.
- The second element can be addressed as:
- number 1: the value of an entry of the input array
- string "value": still the value of an entry of the input array, now retrievable by a string index instead than by number one.
each is a method arguably meant to guarantee the inspection of an associative array both by a number and by a keyword ("key" and "value"):
$foo=array("one"=>1, "two");
$out=each($foo);
//now:
$out[0] //="one"
$out[1] //=1
$out["key"] //="one"
$out["value"] //=1
Of course it is meant to be used on associative arrays; none the less if you use it on normal arrays, it would work, reporting as key the numerical index and obviously as value the value held at that numerical index.
Since each reports only the first item of an array, its main utility is when you use it within a cycle, because each inside a cycle performs returning pointers to the next element until the end of the array is reached - and then arguably it returns false, because the cycle does stops; it is normally used together list() in this case.
list is a php built in function which takes as elements variable names which you can even initialize for the very first time within it: list can only be used at the left of an assignment because it handles the initialized or passed variables as a chain of elements that are meant to get assigned as their own values those of a chain of other elements appearing on the right of the assignment:
list($avar1, $avar2) each($foo);
Since in the above example each produces an array of 2 elements, namely the key/value pair of the currently pointed array entry (out of a loop always and invariably the leading entry), and at the same time list hands over two variable names to be assigned some values, there it happens that to those variables initialized within list() are assigned exactly the two returned values of each: namely the key (or index) and the value of the currently pointed array entry of the array passed as argument to each.
So within a loop, remembering that each is crafted to return a pointer to the subsequent element too, you can recursively inspect either keys or values or both of whatever array by a formula like:
while(list($aKey, $aValue) each($foo)){
print $aKey."=".$aValue." ";
}
I would suggest though to use other ways to loop an array, even an associative one (the ways described at foreach) because after all calling in two functions at every reiteration of a loop may be somewhat anti-economic if (if) the arrays you're dealing with are big ones and your server has to inspect them very often.
It is not uncommon to see list omitting the first parameter:
list($value)=each($array);
This means that you assign only the values leaving out the keys. Of course having introduced inside list the key variable meant to hold the key index would have done no harm, none the less it is legitimate omitting a parameter in the above mentioned fashion, likewise for instance in for loops you can omit parameters between semicolumns:
for($x=0 $x++){}
Note: the loop above omits the stop condition, so it is potentially an infinite cycle: it is assumed some stopping condition is to be nested within the statements held by the loop curly brackets.
|
 |
 |
max & min |
 |
 commonly used |
ARGUMENTS |
RETURNS |
max( array ) ; min( array )
max( el1, el2... ) ; min( el1, el2... ) |
number |
 |
USAGE |
 |
Both function take in either an array, or also a list of subsequent elements; max returns the higher of the value held within the array (or ranked among the list of arguments), and min returns the lower value:
$foo=array(4,5,6);
max($foo); //returns 6
min(4,5,6); //returns 4
If the array or the list is not composed of numbers but of letters, min returns the preceding one in the alphabetical order and max the following one: that is, min shifts leftward, max shifts rightward
$foo=array("a","b","c");
max($foo); //returns c
Capital letters are considered by default as logically preceding lowercase ones, consequently:
max("a", "A"); //returns lowercase a
Also, numbers are considered as following all letters, so:
min(50, "b"); //returns b
Punctuations are considered as anteceding the whole hierarchy.
Considering one capital letter as the representative of all capital letters and a lowercase letter as representing all lowercase letters and one number as representing all numbers and a slash as representing all punctuations, the order may be said:
/Aa1
If by chance you're interested in char Codes of letters or numerical codes of punctuations (for instance to assess which is regarded as "minor" in the hierarchy between a dot and a slash), a tool where you can inspect them can be found here
|
 |
 |
array |
 |
 commonly used |
ARGUMENTS |
RETURNS |
array( argument, argument2 ... ) |
array |
 |
USAGE |
 |
The array function is the standard way to produce an array out of the passed arguments, which must be separated by a comma. Instance:
$array=array(1,2,350,"whatever")
Of course you can also build an Array without taking avail of the array method, namely by indexing all its items directly:
$array[0]="zero"
$array[1]="one"
This method though can yield a few "unpredictable" errors, thence the utility of using the array() method. In fact if you use the procedure of writing down your array entries directly, remember the following:
- The first item should always carry an index, normally zero.
- If by chance you initialize an array this way with an index higher than zero, keep in mind that an array length is to be : it is the amount of , and not the amount of what produces the eventual size of a PHP array.
Unlike javaScript also associative arrays have a length property.
- Following entries after the first declared one may optionally carry no key index: in such case they are considered as indexed with increasing numbers from the first key index (in the simplest case zero). Therefore if by chance you have started indexing your array with, say, 20, a syntax like:
$array[20]="something"
$array[]="something else, arguably"
would imply that the key in within the empty set of square brackets is assumed as being 21.
If you make something like:
$array[30]="something else, arguably"
$array[20]="something"
$array[]="something else, arguably"
The empty set is assumed having an index of, in our example, 31, namely . Also and as already stated, such array has a size of 3, not of 31.
- Array entries declared by using a set of must or a immediately:
$array[0]=0;
$array[]; //no!
that would generate an error: empty brackets want a value being assigned:
$array[0]=0;
$array[]"something";
//ok
- Calling in an entry with an index that doesn't exist returns as type: NULL, and if printed prints an empty string: ''.
To make associative arrays you can use array() separating the key/value pairs with a comma and linking each key with its value by this symbol: :
array("key1"=>"value1", "key2"=>"value2")
Since the syntax which uses the symbol implies the array is associative, if you want you can optionally omit the quotes surrounding the key: as long as you do use the syntax, PHP would understand that the element on the left of such symbol cannot be meant as but a string (if no dollar sign antecedes is, in which latter case it is a variable elsewhere already defined, whose value is now being lent to perform also as a key into this array); but you cannot omit quotes from the values if such values are meant to be strings. My suggestion, use quotes to keep it simpler.
Alternatively, you can build an associative array directly as for a standard array:
$array["akey"]="aValue"
But in this case, namely without resorting to the use of the array function, if the index is a string (for actually associative arrays are sort of omni-potent in their key indexes: they are data structures that accept to be indexed by keys whose data type is and not uniquely as in the case of the standard arrays, and not even just and uniquely a string) such key must then go always in between quotes.
|
 |
 |
range |
 |
 used |
ARGUMENTS |
RETURNS |
range( num, num ) |
array |
 |
USAGE |
 |
It produces an array containing all integers between the first passed number and the second passed number.
If you forget the second argument, NULL is returned. If second argument is lower than first, it seems that an empty array may get produced. If both passed numbers are identical, it produces an array of one entry. If some number is a floating digit, floating fractions will be ignored and the arguments rounded to the digit before the fractional part.
|
 |
 |
explode |
 |
 commonly used |
ARGUMENTS |
RETURNS |
explode( separator, string ) |
array |
 |
USAGE |
 |
It produces an array. Actually it is a String, and not an Array method, but I list it here because of its output.
Takes as second argument the string (strangely enough the string meant to be split is not the first argument!) and divides it by the first argument I named separator as many times as such separator recurs in the string - if it can be found at all of course: the splintered segments of the string are consequently returned as an array:
$foo="hallo world";
$out=explode( " ", $foo);
//between the quotes there is a white space
now $out is an array where $out[0]="hallo" and $out[1]="world".
explode cannot separate letter by letter. To achieve this, in case you need it, you have to use a regular expression handling php method, such as preg_split; a syntax which achieves the last mentioned purpose is:
$out=preg_split( "//", $foo);
That generates an array of 13 entries, for it includes also a leading empty one and trailing empty one for the separator dictated to split the whole string by char and char, and since each line although invisibly starts with a start of line special char and finishes with an end of line special char, Php considers them too as legitimate chars to be included in such a splitting process.
|
 |
 |
implode |
 |
 commonly used |
ARGUMENTS |
RETURNS |
implode( separator, array) |
string |
 |
USAGE |
 |
implode takes in as first argument an array, and joins it by its second argument, which must be a string and is mandatory:
$foo=array(0,1,2,3,4);
print implode($foo, "_");
//prints: 0_1_2_3_4
print implode($foo, "");
//prints: 01234
A strange fact with implode is that if you reverse the argument, the function still works: that is, detects which one is the array and which one is the separator and divides the former by the latter accordingly and regardless of the sequence they are passed.
Esoteric strange thing: note that this no longer applies in case you pass two arrays: if both the first argument and the second are arrays, the first argument is assumed as a collection of separators that are meant to be entry by entry, sequentially used to join among them as many copies of the second array argument as necessary to exhaust all the spearators; that is:
print implode(
array(" separator1 "," separator2 "," separator3 "," separator4 "),
array(1,2,3)
);
/*prints: separator1 Array separator2 Array separator3 Array separator4
yeah, funny */
.
|
 |
 |
compact |
 |
 rarely used |
ARGUMENTS |
RETURNS |
compact( args ) |
associative array |
 |
USAGE |
 |
This function takes in as many arguments as you prefer, either as a list separated by commas or even as an array - which as such would just be recursively unfolded.
These arguments have to be string of names (that is, in between quotes) assigned to currently existing variables: the function would locate those variables and create an output array which is to be an associative array: each key will be one of the name passed, and each value will be the value hold by the variable whose name matches the passed one: example:
$name="John";
$secondName="Smith";
$out=compact("name" , "secondName");
If the name of something which has never been defined earlier (instance: adding into the example above "nonExistantName" to the list of parameters passed to compact) is passed, the entry will be added to the output associative array but will hold no value for there is no variable located with that name.
The scope within which compact will search for such variables is local: that is, invoked within a function will search for corresponding names within the function, not outside of it among the globally defined ones.
|
 |
 |
extract |
 |
 rarely used |
ARGUMENTS |
RETURNS |
extract( array, optionalMODE, optionalPREFIX ) |
variables |
 |
USAGE |
 |
This function takes in as first argument an array.
All those elements within such array whose indexes are strings (that is, the array is an associative one and has some string keys) would be transformed into variables whose existence would affect the scope within which explode has been invoked (instance: within a function would affect only the lifetime of the function and would not affect global settings) and whose values will be the values such keys held in the array: example:
$foo=array("one"=>1,"two"=>2);
extract($foo); //now two variables named $one and $two exist!
print $two;
The other two arguments for extract are optional and are meant to handle conflicting names among the newly created ("extracted") variables and other variables already existing that might carry the same name.
The second parameter (let's call it modal cases) accepts 4 and only 4 possible values, all of them uppercase if passed and no misspellings:
- EXTR_OVERWRITE: flags that you can overwrite variables with identical names.
- EXTR_SKIP: flags that you must bypass variables with conflicting names (that is, if say $two is already defined, it gets not created anew. Keep in mind that PHP considers as "existing" variables those to which some value has been assigned and not those that have just been written down: $two=0 would be respected, but a global variable just written as $two but without assignment would be overwritten mercilessly).
- EXTR_PREFIX_SAME, flags that you have to add the passed prefix (third argument) in case of conflicts.
- EXTR_PREFIX_ALL: flags that you have to pass the prefix (third argument) anyway.
The third argument is an optional prefix for the last two mentioned modal cases. If the last two modal cases are chosen, a prefix argument must be passed, even an empty one as " ".
Such prefix in case of conflicting names would be prefixed along with an underscore sigh: that is:
$two=4; //conflicting variable name put into place;
$foo=array("one"=>1,"two"=>2);
extract($foo, EXTR_PREFIX_SAME, "pref");
//now as far as $two is affected, there exist:
print $two; //prints 4
print $pref_two; //prints 2
|
 |
 |
array_search |
 |
 commonly used |
ARGUMENTS |
RETURNS |
array_search( mixed, array ) |
number or boolean |
 |
USAGE |
 |
Rather than scanning an array via your own loop, you can use array_search: pass to it as its first argument the value to search for, and as its second the array upon which you are searching.
The function shall return a number which is the index of the position of the searched element in the array, if any. Such element is the first found in the array.
If no such element is found, boolean false is returned.
Since both boolean false and zero would both evaluate to false in a comparison with the == sign, so to check whether it returned false or not use either === or !== which are specific to look for an identity also in the Data Type.
$output=array_search( 'foo1', array('foo1', 'foo2', 'foo1') );
The above returns zero being zero the first index where 'foo1' is found.
To check if array_search actually returned a result, thus, use:
if($output !== false){/*found something*/}
If you want to check for all the occurrences of a value and not just for the first you meet, use this syntax:
array_keys(array, valueToSearch)
namely, noting that the arguments using array_keys are reversed to those using array_search:
$output=array_keys( array('foo1', 'foo2', 'foo1'), 'foo1' );
That expression returns an array
Array ( [0] => 0 [1] => 2 )
with as many items as many indexes are found (each item in fact reports an index).
If no element is found, that returns an empty array, so the check is now about the sizeof of the array.
|
 |
 |
array_push & array_pop |
 |
 commonly used |
ARGUMENTS |
RETURNS |
array_push( array, addon );
array_pop( array ) |
array_push: boolean
array_pop: value |
 |
USAGE |
 |
push adds to the array passed as its first argument the element passed as its second argument: it adds it to the end of the array (higher index value). If you pass to it more arguments, it recursively add them all.
pop removes the last (higher index value) element from the argument array. |
 |
 |
array_unshift & array_shift |
 |
 commonly used |
ARGUMENTS |
RETURNS |
array_unshift( array, addon );
array_shift( array ) |
array_unshift: boolean
array_shift: value |
 |
USAGE |
 |
unshift adds to the array passed as its first argument the element passed as its second argument: it adds it to the beginning of the array (lower index value). If you pass to it more arguments, it recursively add them all.
shift removes the first (lower index value) element from the argument array. |
 |
 |
array_slice & array_splice |
 |
 commonly used |
ARGUMENTS |
RETURNS |
array_slice( array, num1, num2 );
array_splice( array, num1, num2, array ); |
array_slice: array
array_splice: array |
 |
USAGE |
 |
The array_slice takes in an array and copies from it a sub-array starting with index num and ending with index num2. If num2 is omitted the end of the array is assumed. The num2 argument is the amount of elements to be taken in: that is:
$foo=array(0,1,2,3,4);
$foo2=array_slice($foo, 2,3);
Such code would assign to $foo2: [2,3,4].
The sub-array, the slice that is, is returned but the original array is neither affected nor stripped of it. The two arrays are independent of each other, no javascript pointer like relationship is entertained.
array_splice does the same as array_slice but removes the extracted slice from the original array.
It can insert new array elements in lieu of the spliced: if this feature wants to be exploited, the new array elements to insert must be passed as the fourth argument. Passing such fourth argument and yet setting as zero the third argument would produce an insertion of the elements passed as fourth argument: these latter would be placed in the array soon after the index number indicated by the second argument. In other words, setting the third argument as zero and then passing the fourth produces no longer any splicing but just (though puzzling) an insertion.
The inserted substitutes affect the original. Such substitutes must be passed as its fourth argument. If substitutes are not passed, the slice gets just permanently removed from the original array thus performing the standard splicing. |
 |
 |
array_merge |
 |
 commonly used |
ARGUMENTS |
RETURNS |
array_merge(array1, array2...) |
array |
 |
USAGE |
 |
This is the function used to weld more arrays into one, as many as the passed arguments are - which have to be arrays: but if they are not, the array_merge function is smart enough to understand it just has to add those entries as additional ones wherever they appear in the list of passed arguments:
$foo=array(0,1,2,3);
$foo2=array(5,6,7);
$foo3=array_merge($foo, 4, $foo2);
Original arrays are not affected. |
 |
 |
array_unique & array_diff & array_intersect |
 |
 used |
ARGUMENTS |
RETURNS |
array_unique( array )
array_diff(array1, array2 ...)
array_intersect(array1, array2 ...) |
array |
 |
USAGE |
 |
- array_unique returns an array of all those entries in the input array which have no duplicates in the input array itself. Example:
$foo=array(1,2,2,3,3);
print implode(array_unique($foo),",");
//prints: 1,2,3, skipping the duplicates
In case the input array is empty returns an empty array.
- array_diff takes in as arguments more arrays: returns an array of all those entries in the first input array which are not in common with the other arrays Example:
$foo=array(1,2,3,4,5);
$foo2=array(4,3);
$foo3=array(0,5);
print implode(array_diff($foo, $foo2, $foo3),",");
//prints: 1,2
1 and 2 are the only entries in the first array which do not recur in at least one of the other arrays.
If you pass one array only, it triggers an error.
- array_intersect takes in as arguments more arrays: returns an array of all those entries in the first input array which are in common with the other arrays. Example:
$foo=array(1,2,3,4,5);
$foo2=array(1,4,3);
$foo3=array(0,5,2,3);
print implode(array_intersect($foo, $foo2, $foo3),",");
//prints: 3
3 is the only entry in the first array which recurs in all the others too.
If you pass one array only, it triggers an error.
|
 |
 |
array_keys & array_values |
 |
 commonly used |
ARGUMENTS |
RETURNS |
array_keys(array, optionalElement);
array_values(array) |
array |
 |
USAGE |
 |
The array_keys takes in an array, ideally an associative one, and produces out of it another array whose indexes are numbers and whose values are the keys of the original input array: useful to list keys of associative arrays:
$foo=array("one"=>1, "two"=>2, "three"=>3, "other"=>1);
$foo2=array_keys($foo);
print implode($foo2," ");
//prints: one two three other
The second argument which is optional would order array_keys to report and list in the output array only those keys which held the same value as the second argument: in the example above:
$foo2=array_keys($foo, 1);
print implode($foo2," ");
//prints: one other, for only those keys hold 1 as their value.
of course, would such values have been strings, the 2nd argument should have been passed in quotes: "somearg value".
Please for array_keys see also array_search.
array_values merely returns a numerically indexed array with all the values of the input array: useful to turn quickly an associative array into a numerically indexed one.
|
 |
 |
array_reverse & array_flip |
 |
 commonly used |
ARGUMENTS |
RETURNS |
array_reverse(array);
array_flip(array) |
array |
 |
USAGE |
 |
The array_reverse capsizes the order of an array: that is, it inverts it. No sorting takes place, the order of the entries is simply reversed back to front.
array_flip doesn't invert the order of the entry, but for each entry it swaps the key with the value!
|
 |
 |
sort & natsort & natcasesort & rsort |
 |
 commonly used |
ARGUMENTS |
RETURNS |
sort(array);
natsort(array)
natcasesort(array)
rsort(array) |
nothing |
 |
USAGE |
 |
The sort function
takes in an array and obviously sorts it alphabetically. It returns nothing, the original is affected.
As far as what hierarchy it follows when ordering, the same rule
/Aa1
mentioned for max & min is applied here too.
Keep in mind that if the array you pass is an associative array, what is sorted are the values, and the returned array is a standard numerically indexed array arranged after alphabetically ordered values.
rsort sorts as above but in the order inverse, namely not /Aa1 but:
1aA/.
$foo=array(1,2,"a","b","A","//");
sort($foo);
print implode($foo," ");
the above prints: // A a b 1 2
rsort($foo);
print implode($foo," ");
the above prints: 2 1 b a A //
In case of arrays that hold strings and not numbers, the sorting processes would not be natural: that is, if you have an array like:
$foo=array('a1','a2','a3','a10','a11');
sort($foo);
print implode( $foo,',' );
that would print:
a1, a10, a11. a2, a3
That is, it would arrange the strings as strings, without discriminating whether in within a string order also a numerical order should have been respected [for more on this excellent and brief external source: http://www.naturalordersort.org/].
The function named natsort fixes this:
$foo=array('a1','a2','a3','a10','a11');
natsort($foo);
print implode( $foo,',' );
now prints the expected:
a1,a2,a3,a10,a11
The last issue is that normally as already stated capital cases may be listed before uppercases even if you use natsort:
$foo=array('a1','a2','a3','A10','a11');
natsort($foo);
print implode( $foo,',' );
that prints:
A10,a1,a2,a3,a11
with the leading A10: to fix this too use natecasesort which is case insensitive:
$foo=array('a1','a2','a3','A10','a11');
natcasesort($foo);
print implode( $foo,',' );
which finally prints:
a1,a2,a3,A10,a11
|
 |
 |
ksort & krsort |
 |
 commonly used |
ARGUMENTS |
RETURNS |
ksort(array);
krsort(array) |
nothing |
 |
USAGE |
 |
The very same rules said for sort & rsort are perfectly valid here: only, ksort and krsort sort the input arrays not by their values but by their keys: so they are useful mostly in the case of associative arrays with many literal (string) key indexes.
|
 |
 |
asort & arsort |
 |
 commonly used |
ARGUMENTS |
RETURNS |
asort(array);
arsort(array) |
nothing |
 |
USAGE |
 |
The very same rules said for sort & rsort are perfectly valid here: asort and arsort still sort the input arrays by their values but unlike sort & rsort that replaced all their keys with numerical indexes, asort & arsort do not replace the keys, but conversely while the sorting process is performed as values dictates, all the corresponding keys too follow the reordering process which the values undergo: so the original key/value pairs are preserved, although reordered by values.
Definitely, these functions are useful mostly if not uniquely in the case of associative arrays.
|
 |
 |
usort & uksort & uasort |
 |
 commonly used |
ARGUMENTS |
RETURNS |
usort(array, stringFunction);
ursort(array, stringFunction)
uksort(array, stringFunction) |
nothing |
 |
USAGE |
 |
These are the built in php sorting function where you can custom your sorting process.
They work as follows, their first argument is an array, the second argument must go in between quotes and it has to be the name given to a function, even a customed one but in such case obviously defined within the script scope; these u-sort php function would recursively locate and apply the function with such name upon the input array passed as first argument, executing this fore mentioned customed function respectively against:
- usort: the values of the passed array.
- uksort: the keys of the passed array.
- uasort: both the values and the keys of the passed array.
That is, an example can be:
$foo=array("four"=>4, "two"=>2, "five"=>5, "one"=>1, "three"=>3);
usort($foo, "nameOfComparisonFunction");
As Leon Atkinson says in his Core Php Programming:
such « comparison function must return a signed integer. If it returns zero, then the 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.»
This function could be created by yourself, and by and large it should not be a php built in one although these sorting procedures would accept as built in php functions at least three of them: strcmp, strnatcmp and strnatcasecmp.
Your custom function must not only return an integer as just said, but should also have two arguments, meant to be the two elements that undergo the comparison at each reiteration.
This means that if we want to sort, for instance, after the length of the texts, we can conceive a personal function as follows:
function compare($left, $right){
$left.=""; //turned into a string;
$right.=""; //turned into a string;
if( strlen($left) == strlen($right) ){return 0;}
elseif( strlen($left) < strlen($right) ){return -1;}
elseif( strlen($left) > strlen($right) ){return 1;}
}
Or, arranging your compare function in the Leon Atkins style:
function compare($left, $right){
$left.="";//turned into a string;
$right.=""; //turned into a string;
return ( strlen($left)-strlen($right) );
}
Alternatively, if you want you can to use strcmp and strnatcmp or (even better) strnatcasecmp which are php built in functions:
$foo=array("four"=>4, "two"=>2, "five"=>5, "one"=>1, "three"=>3);
usort($foo, "strnatcmp");
//or:
usort($foo, "strnatcasecmp");
My personal syggestion is to use strnatcasecmp because it is the built in function best suited to perform a perfect natural comparison and thus to return a perfectly naturally ordered array once such comparison is what you take avail of in order to accomplish a sorting process.
A full fledged example:
$foo=array("four"=>4, "two"=>2, "five"=>5, "one"=>1, "three"=>3);
usort($foo, "compare");
foreach($foo as $key=>$value){print $key."=".$value."<br>";};
The printed output is in this case:
0=2
1=5
2=1
3=3
4=4
In fact, usort takes in only the values and exactly like sort it strips off the keys to replace them with standard numbers. Since the values had to be arranged accordingly to their length given the way we defined our custom compare function and since the length of these values is always identical (they are all one digit long) their order is apparently confused: in fact they all appeared on the same footing to the comparison function as far as their length was concerned.
See what happens with the other two functions:
uksort($foo, "compare");
foreach($foo as $key=>$value){print $key."=".$value."<br>";};
This must order by the keys, and particularly by the length of the text of the keys. Correctly, it returns:
one=1
two=2
five=5
four=4
three=3
the shorter keys on top, the longer ones at bottom.
See now:
uasort($foo, "compare");
foreach($foo as $key=>$value){print $key."=".$value."<br>";};
It prints:
two=2
five=5
one=1
three=3
four=4
in fact, uasrot exactly like asort sorts by the values, which as we saw in the case of usort are all equivalent; but uasort doesn't replace the keys with numerical indexes but swaps also the original keys, thus performing a reordering by values but making keys follow instead of discarding them in the process!
If you would have used the built in strnatcasecmp function:
uasort($foo, "");
foreach($foo as $key=>$value){print $key."=".$value."<br>";};
it prints:
one=1
two=2
three=3
four=4
five=5
or with uksort:
uksort($foo, "");
foreach($foo as $key=>$value){print $key."=".$value."<br>";};
it prints:
five=5
four=4
one=1
three=3
two=2
see, the keys are perfectly ordered in alphabetical rank.
|
 |
 |
array_multisort |
 |
 commonly used |
ARGUMENTS |
RETURNS |
array_multisort(array1, mode, array2, mode ...); |
boolean |
 |
USAGE |
 |
This is the built in php function that performs multisorting processes: that is, given a number of arrays higher than 1, you may want to sort one array being sure that the sorting process that affects it and the reordering it undergoes trigger similar effects also on other arrays thus that the original symmetry their entries had with the first array that underwent the sorting process are preserved.
You must pass the arrays alternating them with the mode you want each sorted (unfortunately this seems -so a few manuals say- mandatory): the modal values must be either:
- SORT_ASC (sorts with ascending order)
- SORT_DESC (sorts with descending order)
$foo=array("office", "kitchen", "car", "bat");
$foo2=array("boss", "cook", "driver", "player");
array_multisort($foo, SORT_ASC, $foo2, SORT_ASC);
print implode($foo," ");
print "<br>";
print implode($foo2," ");
That code would print:
bat car kitchen office
player driver cook boss
as you see the first line is alphabetically sorted: the second is not, but still respects the job/role symmetry the two arrays originally had before the first underwent the sorting process: by sorting it using array_multisort we made it possible to preserve the symmetries.
Despite a few manuals say that the mode must be written, I found that if you don't no error is reported, thus also:
array_multisort($foo, $foo2);
would do.
If you pass only one array, it just gets sorted, no error ensues.
|
 |
 |
array_walk |
 |
 commonly used |
ARGUMENTS |
RETURNS |
array_walk(array, stringFunction); |
boolean |
 |
USAGE |
 |
I made a slightly more powerful javascript emulation of this php function. The javascript emulation can be found here.
as for the Php version, this function is meant to perform recursively upon the array passed as first argument, the operations dictated by a custom function defined somewhere in the script: the name of such function must be passed as a string (in between quotes, that is) to the array_walk function as its second argument.
This function must be created by yourself, it cannot be a php built in one.
The custom function must allow mandatory for one argument only. The operations it dictates are performed on each entry of the array passed as first argument. Instance:
$foo=array(3,3,3,4);
function myfunc( $arg ){
$arg+=1;
print $arg;
}
array_walk($foo, "myfunc");
print "<br>".implode($foo, ",");
We'd expect the last printing process would print 4,4,4,5 but it does not: therefore I doubt that array_walk affects the original array always and anyway as the documentations declare. None the less, the operations within the custom function are performed as the printing process within the function proved, for it did print 4445
|
 |
 |
shuffle |
 |
 commonly used |
ARGUMENTS |
RETURNS |
shuffle( array ) |
nothing |
 |
USAGE |
 |
This function just shuffles the entries of an array, randomly. The original array is affected and its entries should get casually remixed. To be sure that each new shuffle would generate a new combination do call the srand function before the shuffling (and not the mt_srand).
I say should because actually all shuffling processes generate random positions by taking in the current time: this means that you may have to instruct your script that at each shuffle it has to take in a new time and not just the one it did when loaded the first time (which persists).
To achieve that you can use this syntax: srand(time()); namely:
$foo=array(0,1,2,3,4,5);
srand(time());
shuffle($foo);
print implode($foo," ");
Even better, you could use the microtime function: it counts the number of milliseconds on the computer clock (whereas time just counts the number of seconds elapsed since january 1, 1970), consequently microtime returns a more volatile number; since it returns such number, strangely, as a string, you have cast it into a number first, preferably of the double data type, then you multiply it for a number that takes in a lot of ending numbers to increase the differences: here is why such strange alternative syntax:
srand( (double)microtime() * 10000000 );
If shuffle takes in an associative array, it shuffles its values and replaces the keys with numerical indexes! Original affected!
|
 |
 |
array_rand |
 |
 used |
ARGUMENTS |
RETURNS |
array_rand( array, num ) |
number | array |
 |
USAGE |
 |
This function extracts a random entry from an array and returns its key (that is, not the value, I insist: the key).
You do have to call in srand as I described in shuffle
$foo=array('one', 'two','three','four');
srand ((double) microtime() * 10000000);
print array_rand($foo);
//prints: a num from 0 to 3
Such returned number is a random key within the boundaries of the input array: to get its equivalent entry you may therefore do:
print $foo[ array_rand($foo) ];
that would print the value of the randomly extracted key.
This function accepts a second parameter which must be a number: it says how many elements you want to extract randomly from the input array: in such case it doesn't return any longer a number but an array of extracted keys:
$foo=array('one', 'two','three','four');
srand ((double) microtime() * 10000000);
print implode( array_rand($foo, ), ',');
//prints: an array of 3 random KEYS
In this case to extract the value is more convenient to assign the randomized array to another variable:
$foo=array('one', 'two','three','four');
srand ((double) microtime() * 10000000);
$extracted=array_rand($foo, );
//get the values:
print $foo[ $extracted[] ];
print $foo[ $extracted[] ];
print $foo[ $extracted[] ];
It works with associative arrays as well.
The second optional parameter must not exceed the length [ sizeof] of the array or an error is returned. Note that saying the length, it means that if you say in our example 4, although an index 4 does not exist in the input array because indexes are counted from zero onward and thus in the case of 4 entries end with 3, none the less no error ensues.
But if you pass zero, an error ensues (a few manuals say zero is ok: it is not, triggers a warning to say the least).
|
|
|