Add value to php array. Adding an element to the beginning of the array. Adding and Removing Array Elements
Adding elements to an array
If the array exists, additional elements can be added to it. This is done directly using the assignment operator (equal sign) in the same way as assigning a value to a string or number. In this case, you don’t have to specify the key of the added element, but in any case, square brackets are required when accessing the array. Adding two new elements to $List, we'll write:
$List = "pears";
$List = "tomatoes";
If the key is not specified, each element will be added to the existing array and indexed by the next ordinal number. If we add new elements to the array from the previous section, whose elements had indexes 1, 2 and 3, then pears will have index 4, and tomatoes will have index 5. When you explicitly specify an index, and the value with it is already exists, the existing value at that location will be lost and replaced with a new one:
$List = "pears";
$List = "tomatoes";
Now the value of the element with index 4 is “tomatoes”, and the element “oranges” is no longer there. I would advise not to specify a key when adding elements to an array, unless you specifically want to overwrite any existing data. However, if strings are used as indexes, the keys must be specified so as not to lose values.
We will try to add new elements to the array by rewriting the soups.php script. First by printing source elements array, and then the original ones along with the added ones, we can easily see the changes that have occurred. Just as you can find out the length of a string (the number of characters it contains) using the strlen() function, it is also easy to determine the number of elements in an array using the count() function:
$HowMany = count($Array);
- Open soups.php file in text editor.
- After initializing the array using the array() function, add the following entry: $HowMany = count($Soups);
- Add three additional elements to the array. $Soups["Thursday"] = "Chicken Noodle";
- Count the elements in the array and print this value. $HowManyNow = count($Soups);
- Save the script (Listing 7.2), upload it to the server and test it in the browser (Fig.).
print("The array contains $HowMany elements.
\n");
The count() function will determine how many elements are in the $Soups array. By assigning this value to a variable, it can be printed.
$Soups["Friday"] = "Tomato";
$Soups["Saturday"] = "Cream of Broccoli";
print("The array now contains $HowManyNow elements.
\n");
Listing 7.2 You can directly add one element at a time to an array by assigning a value to each element using the appropriate operator. The count() function can be used to find out how many elements are in an array.
1
2
3
4
5 6 $Soups = array(
7 "Monday"=>"Clam Chowder",
8 "Tuesday"=>"White Chicken Chili",
9 "Wednesday"=>"Vegetarian");
11 print("The array contains $HowMany
elements.
\n");
12 $Soups["Thursday"] = "Chicken Noodle";
13 $Soups["Friday"] = "Tomato";
14 $Soups["Saturday"] = "Cream of
Broccoli";
15 $HowManyNow = count($Soups);
16 print("The array now contains
$HowManyNow elemente.
\n");
17 ?>
18
19
Appeared in PHP 4.0 new feature, which allows you to add one array to another. This operation can also be called merging or concatenation of arrays. The array_merge() function is called as follows:
$NewArray = array_merge($OneArray, $TwoArray);
You can rewrite the soups.php page using this function if you are working on a server that has PHP 4.0 installed.
Merging two arrays
- Open the soups.php file in a text editor if it is not already open.
- After initializing the $Soups array, count its elements and print the result. $HowMany = count($Soups);
- Combine two arrays into one. $TheSoups = array_merge($Soups, $Soups2);
- Count the elements of the new array and print the result. $HowMany3 = count($TheSoups);
- Close PHP and the HTML document. ?>
- Save the file (Listing 7.3), upload it to the server and test it in the browser (Fig.).
print("The $Soups array contains $HowMany elements.
\n");
- Create a second array, count its elements and also print the result.
"Thursday"=>"Chicken Noodle",
"Friday"=>"Tomato",
"Saturday"=>"Cream of Broccoli");
$HowMany2 = count($Soups2);
print("The $Soups2 array contains $HowMany2 elements.
\n");
Make sure that the arrays are arranged in this order ($Soups, then $Soups2), that is, the elements of Thursday and Friday should be added to the elements of Monday of Wednesday, and not vice versa.
print("The $TheSoups array contains
-$HowMany3 elements.
\n");
Listing 7.3 The Array_merge() function is new. This is one of several additional features in PHP 4.0 designed to work with arrays. Using arrays you can save a lot of time.
1
2
3
4
5 6 $Soups = array!
7 "Monday"=>"Clam Chowder",
"Tuesday"=>"White Chicken Chili",
8 "Wednesday"=>"Vegetarian"
9);
10 $HowMany = count($Soups);
11 print("The $Soups array contains $HowMany elements.
\n");
12 $Soups2 = array(
13 "Thursday"=>"Chicken Noodle",
14 "Friday"=>"Tomato",
15 "Saturday"=>"Cream of Broccoli"
16); .
17 $HowMany2 = count($Soups2);
18 print ("The $Soups2 array contains $HowMany2 elements.
\n");
19 $TbeSoupe = array_merge ($Soups, $Soups2);
20 $HowMany3 = count ($TheSoups) ;
21 print ("The $TheSoups array contains .$HowMany3 elements.
\n");
22 ?> "
23
24
Be careful when adding elements to an array directly. This is done correctly like this: $Ar ray = "Add This"; iyai$Aggau = "Add This";, but it’s correct like this: $Aggau = "Add This";. If you forget to put the parentheses, the added value will destroy the existing array, turning it into a simple string or number.
PHP 4.0 has several new functions for working with arrays. Not all of them are discussed in the book. However, complete information on this subject is contained in the PHP language manual, which can be found on the PHP website. Be careful not to use new features unique to PHP 4.0 if your server is running PHP 3.x.
There are many functions and operators for converting arrays in PHP: Collection of functions for working with arrays
There are several ways to add an array to an array using PHP and all of them can be useful for certain cases.
"Operator +"
This is a simple but insidious way:
$c = $a + $b
This way, only those keys are added that are not already in the $a array. In this case, the elements are appended to the end of the array.
That is, if the key from the array $b is not present in the array $a, then an element with this key will be added to the resulting array.
If the $a array already contains an element with such a key, then its value will remain unchanged.
In other words, changing the places of the terms changes the sum: $a + $b != $b + $a - this is worth remembering.
Now here's a more detailed example to illustrate this:
$arr1 = ["a" => 1, "b" => 2]; $arr2 = ["b" => 3, "c" => 4]; var_export($arr1 + $arr2); //array (// "a" => 1, // "b" => 2, // "c" => 4, //) var_export($arr2 + $arr1); //array (// "b" => 3, // "c" => 4, // "a" => 1, //)
array_merge() function
You can use this function as follows:
$result = array_merge($arr1, $arr2)
It resets numeric indices and replaces string ones. Great for concatenating two or more arrays with numeric indexes:
If the input arrays have the same string keys, then each subsequent value will replace the previous one. However, if the arrays have the same numeric keys, the value mentioned last will not replace the original value, but will be added to the end of the array.
array_merge_recursive function
Does the same thing as array_merge, except it recursively goes through each branch of the array and does the same with its children.
array_replace() function
Replaces array elements with elements of other passed arrays.
array_replace_recursive() function
Same as array_replace but processes all branches of the array. Help for array_replace_recursive.
Other features
There are a number of useful functions for working with arrays in PHP, the existence of which is advisable to know. You can read about them at the link:
date: 2010-07-09
First of all, let's create an array. Let there be an array of individual cards of the same suit (spades = s). Let's call him var cards.
Var cards = ["8s","9s","Ts","Js","Qs"]; // 5 elements (cards of the same suit from 8 to queen)
As you can see, there are 5 elements in our array, each of which has its own unique index. Let us remind you once again that indexing of array elements starts from 0, do not forget about this, i.e. in our example, the first element of the array ("8s") is 0, the last ("Qs") is 4.
Adding an element to the end of an array
Knowing that in our array var cards there are only 5 elements and the last index ends with 4, then we can add a new element to the array like this:
Var cards = ["8s","9s","Ts","Js","Qs"]; // 5 elements (cards of the same suit from 8 to queen) cards = "Ks"; //added a new element to the end of the array, now there are 6 elements in the array
The difficulty with this approach is that if the array contains many elements, counting them can be very inconvenient. For such cases there is a simpler solution - the array property length, which determines the length of the array, i.e. number of elements in the array. Let's see an example:
Launch! var cards = ["8s","9s","Ts","Js","Qs"]; // 5 elements (cards of the same suit from 8 to queen) cards = "Ks"; /* add a new element to the array using the lenght property */ for(i = 0; iIn line 4 of our code we added an entry in the form cards;. This code is identical cards;, since the property length, as mentioned above, determines the number of all elements in the array. In other words, we don’t need to count the elements, instead we write the array itself, put a dot and use the keyword length. On line 7 we also apply the property length- first we determine the start of the counter from 0, then there is a condition in which we write, if the counter value is less than the length of the array, then we increase the counter by one and execute the code in curly braces (in the body of the loop), where we display the array elements using the alert( ), you can use document.write(). In other words, everything looks like this:
0 is less than 6? Yes, less. We increase the counter by 1 and execute the code in the body of the loop
1 is less than 6? Yes, less. We increase the counter by 1 and execute the code in the body of the loop
2 is less than 6? Yes, less. We increase the counter by 1 and execute the code in the body of the loop
.....................................................
Is 6 less than 6? No. The cycle stops.
push() method
In addition to the methods described above, there is also a method push(), with which we can add any type of data, and even a variable, to the end of the array. In this case, there can be several elements at once, which are written separated by commas in parentheses. Let's look at an example:
Launch! var cards = ["8s","9s","Ts","Js","Qs"]; // 5 elements (cards of the same suit from 8 to queen) cards.push("Ks","As"); /* add new elements to the array using the push() method */ for(i = 0; iAdding an element to the beginning of an array
unshift() method
If you need to add elements at the very beginning of the array, use the method unshift. It works on the same principle as the push() method.
Launch! var cards = ["8s","9s","Ts","Js","Qs"]; // 5 elements (cards of the same suit from 8 to queen) cards.unshift("5s","6s","7s"); /* add new elements to the array using the unshift() method */ for(i = 0; iIn this chapter:
An array is a special type of variable that stores many data elements. An array allows you to access separately any of its constituent elements (since they are stored separately inside the array), and it is also possible to copy or process the entire array.
PHP arrays are untyped, meaning that the elements of the array can be of any type, and different elements in the array can have different types. In addition, PHP arrays are dynamic, which means that there is no need to declare a fixed size and new elements can be added at any time.
Array Basics
To work with arrays, you need to learn two new concepts: elements and indices. Elements are values stored in an array; the values can be of absolutely any type. Each element can be accessed by its unique index. The index can be an integer or a string.
Arrays can be divided into two types: index, in which only an integer is used as the index value, and associative, where the index value can be either a string or a number. Often in associative arrays the index is called: “key”.
Index arrays are usually called simply "arrays", and associative arrays are called "hashes", "associative" or "dictionaries".
Creating an Array
There are three ways to create arrays in PHP. The first way is to create it using the special array() function. The function takes as arguments any number of key => value pairs separated by commas or just values also separated by commas. It returns an array that can be assigned to a variable.
Since you don't have to specify a key, values can be added to the array without specifying one. If a key is not specified, PHP will use numeric indexes. By default, elements will be numbered starting from zero. Arrays with numeric indexes allow you to simply add an element, and PHP will automatically use the previous largest integer key value incremented by 1.
You can also specify a key for individual elements:
"c", "d"); var_dump($my_array); ?>
When you run this example, you may notice that the last element ("d") was assigned to the key 8 . This happened because the largest value of the integer type key before it was 7 .
Now let's look at creating an associative array using the array() function. An associative array is written a little differently: to add an element, the key => value format is used.
"30", "February" => "28/29 (29 happens every four years)", "March" => "31", "April" => "30", "May" => "31", " June" => "30", "July" => "31", "August" => "31", "September" => "30", "October" => "31", "November" => " 30", "December" => "31"); ?>
With the indentation you see in this example, it is easier to add elements to the array than when they are written on one line.
Now let's look at the second way to create an array: using square brackets, instead of the special array() function:
"bar", "bar" => "foo"); // another way to create an array $my_array = ["foo" => "bar", "bar" => "foo"]; ?>
There is no difference between these arrays, except for the difference in spelling.
Please note that in PHP, arrays can contain keys of int and string types simultaneously, i.e. PHP doesn't differentiate between indexed and associative arrays.
"bright", "wheel" => "round", 10 => "house", -5 => 290]; ?>
Note: When choosing a name for an array, be careful not to use a name that is the same as another variable, since they share a common namespace. Creating a variable with the same name as an existing array will delete the array without producing any warnings.
The third way to create arrays will be discussed in the “Adding and Removing Array Elements” section.
Index Conversion
As mentioned at the very beginning of the chapter, a key can be one of two types: string or integer. Therefore, keys that do not match one of these types will be converted:
- If the key is a string that contains a number, it will be converted to type integer. However, if the number is an invalid decimal integer, such as "09", then it will not be converted to an integer.
- A real number (float) will also be converted to an integer - the fractional part in this case is discarded. For example, if the key value is 5.4, it will be interpreted as 5.
- The boolean type (bool) will also be converted to integer. For example, if the key value is true, then it will be converted to 1, and the key with the value false will be converted to 0 accordingly.
- If type null is used, it will be converted to the empty string.
- Objects and arrays cannot be used as keys.
If multiple elements in an array declaration use the same key, then only the last one will be used and all others will be overwritten.
"a", "1" => "b", // keys are converted to number 1 1.5 => "c", true => "d"); var_dump($my_array); ?>
In the example given, all keys will be converted to one, based on this, the array will contain only one element, the contents of which will be overwritten 3 times, as a result, its value will become "d".
Accessing Array Elements
Array elements are accessed using square brackets that indicate the index/key: array.
"milk", 2 => "foo"); echo $my_array["Chocolate"], "
"; echo $my_array; ?>
Another way to access array elements is to use direct array dereference.
hello world! ?>
This example shows that you can access the index of an array returned as the result of a function or method call.
Adding and Removing Array Elements
Now that you have the basic concepts of arrays, let's look at ways to write values to an array. An existing array can be modified by explicitly setting values in it. This is done by assigning values to an array.
The operation of assigning a value to an array element is the same as the operation of assigning a value to a variable, except for the square brackets () that are added after the array variable name. The index/key of the element is indicated in square brackets. If no index/key is specified, PHP will automatically select the smallest unoccupied numeric index.
"zero", 1 => "one"); $my_arr = "two"; $my_arr = "three"; var_dump($my_arr); // assignment without specifying the index/key $my_arr = "four"; $my_arr = "five"; echo "
"; var_dump($my_arr); ?>
To change a specific value, you simply assign a new value to an existing element. To remove any element of an array with its index/key or to completely remove the array itself, use the unset() function:
Note: As mentioned above, if an element is added to an array without specifying a key, PHP will automatically use the previous largest integer key value increased by 1. If there are no integer indexes in the array yet, then the key will be 0 (zero).
Note that the largest integer value of the key does not necessarily exist in the array at the moment, this may be due to the removal of array elements. After elements have been removed, the array is not reindexed. Let's take the following example to make it clearer:
"; print_r($my_arr); // Add the element (note that the new key will be 3 instead of 0). $my_arr = 6; echo "
"; print_r($my_arr); // Do reindexing: $my_arr = array_values($my_arr); $my_arr = 7; echo "
"; print_r($my_arr); ?>
This example used two new functions, print_r() and array_values(). The array_values() function returns an indexed array (re-indexes the returned array with numeric indices), and the print_r function works like var_dump, but outputs arrays in a more readable form.
Now we can look at the third way to create arrays:
The example showed a third way to create an array. If the $weekdays array has not yet been created, it will be created. However, this type of array creation is not recommended because if the $weekdays variable has already been created and contains a value, it may cause unexpected results from the script.
If you are in doubt about whether a variable is an array, use the function is_array. For example, the check can be done as follows:
"; $no = "regular string"; echo is_array($no) ? "Array" : "Not an array"; ?>
Looping through an array
The foreach loop operator sequentially iterates through all the elements of an array. It only works with arrays and objects, and if used with variables of other types or uninitialized variables, an error will be generated. There are two types of syntax for this loop. The first kind of syntax looks like this:
Foreach ($array as $value) (instructions)
The loop will iterate over the given array - $array (the name of the array is substituted for $array). At each iteration, the value of the current element is assigned to the variable $value (you can specify any other variable name). The foreach loop operator is very convenient because it itself loops through and reads all the elements of the array until the last one is reached. It allows you to avoid constantly remembering the fact that array indexing starts from zero and never goes beyond the array, which makes the loop construction very convenient and helps to avoid common mistakes. Let's see how it works with an example:
The second type of foreach syntax looks like this:
Foreach ($array as $key => $value) (instructions)
When using this form of syntax, at each iteration the value of the current key is additionally assigned to the variable $key (you can specify any other variable name):
$value) ( echo "[$key] => ", $value, "
";
}
?>
To be able to directly change array elements within a loop, you need to use a reference. In this case, the value will be assigned by reference.
Note: The reference to the last element of the array remains even after the foreach statement has completed. Therefore, it is recommended to remove it using the unset() function as shown in the example above. Let's see what happens if we don't use unset():"; foreach ($numbers as &$num) ( echo $num, " "; ) ?> One thing to note is that the reference can only be used if the array being iterated is a variable. The following code will not work:
array_pad
Adds several elements to the array.
Syntax:
Array array_pad(array input, int pad_size, mixed pad_value)
The array_pad() function returns a copy of the input array to which elements with pad_values have been added, so that the number of elements in the resulting array is pad_size.
If pad_size>0, then the elements will be added to the end of the array, and if<0 - то в начало.
If the value of pad_size is less than the elements in the original input array, then no addition will occur and the function will return the original input array.
Example of using array_pad() function:
$arr = array(12, 10, 4);
$result = array_pad($arr, 5, 0);
// $result = array(12, 10, 4, 0, 0);
$result = array_pad($arr, -7, -1);
// $result = array(-1, -1, -1, -1, 12, 10, 4)
$result = array_pad($arr, 2, "noop");
// will not add
array_map
Apply a custom function to all elements of the specified arrays.
Syntax:
Array array_map(mixed callback, array arr1 [, array ...])
The array_map() function returns an array that contains the elements of all specified arrays after processing by the user callback function.
The number of parameters passed to the user-defined function must match the number of arrays passed to array_map().
Example of using the array_map() function: Processing a single array
return $n*$n*$n;
}
$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
?>
Array(
=> 1
=> 8
=> 27
=> 64
=> 125
)
Example of using the array_map() function: Processing multiple arrays
return "The number $n in Spanish is $m";
}
function map_Spanish($n, $m) (
return array ($n => $m);
}
$a = array(1, 2, 3, 4, 5);
$b = array("uno", "dos", "tres", "cuatro", "cinco");
$c = array_map("show_Spanish", $a, $b);
print_r($c);
$d = array_map("map_Spanish", $a , $b);
print_r($d);
?>
The given example will output the following:
// printout of $cArray(
=> Number 1 in Spanish - uno
=> Number 2 in Spanish - dos
=> Number 3 in Spanish - tres
=> Number 4 in Spanish - cuatro
=> Number 5 in Spanish - cinco
)
// printout of $dArray(
=> Array
=> uno
)
=> Array
=> dos
)
=> Array
=> tres
)
=> Array
=> cuatro
)
=> Array
=> cinco
)
Typically the array_map() function is used on arrays that have the same size. If arrays have different lengths, then the smaller ones are padded with elements with empty values.
It should be noted that if you specify null instead of the name of the processing function, an array of arrays will be created.
Example of using the array_map() function: Creating an array of arrays
$b = array("one", "two", "three", "four", "five");
$c = array("uno", "dos", "tres", "cuatro", "cinco");
$d = array_map(null, $a, $b, $c);
print_r($d);
?>
The given example will output the following:
Array(
=> Array
=> 1
=> one
=> uno
)
=> Array
=> 2
=> two
=> dos
)
=> Array
=> 3
=> three
=> tres
)
=> Array
=> 4
=> four
=> cuatro
)
=> Array
=> 5
=> five
=> cinco
)
Function supported by PHP 4 >= 4.0.6, PHP 5
array_pop
Retrieves and removes the last elements of an array.
Syntax:
Mixed array_pop(array arr);
The array_pop() function pops the last element from the array arr and returns it, removing it afterwards. With this function we can build stack-like structures. If the array arr was empty, or it is not an array, the function returns the empty string NULL.
After using the array_pop() function, the array cursor is set to the beginning.
Example of using array_pop() function:
$fruits = array_pop($stack);
print_r($stack);
print_r($fruits);
?>
The example will output the following:
Array(
=> orange
=> banana
=> apple
)
Function supported by PHP 4, PHP 5
array_push
Adds one or more elements to the end of the array.
Syntax:
Int array_push(array arr, mixed var1 [, mixed var2, ..])
The array_push() function adds elements var1, var2, etc. to the array arr. It assigns them numeric indices - exactly the same as it does for standard .
If you only need to add one element, it might be easier to use this operator:
Array_push($Arr,1000); // call the function$Arr=100; // the same thing, but shorter
Example of using array_push() function:
array_push($stack, "apple", "raspberry");
print_r($stack);
?>
The example will output the following:
Array(
=> orange
=> banana
=> apple
=> raspberry
)
Please note that the array_push() function treats the array as a stack and always adds elements to the end.
Function supported by PHP 4, PHP 5
array_shift
Retrieves and removes the first element of an array.
Syntax:
Mixed array_shift(array arr)
The array_shift() function takes the first element of the array arr and returns it. It is very similar to array_pop(),
but it only gets the initial, not the final element, and also produces a rather strong “shake-up” of the entire array: after all, when extracting the first element, you have to adjust all the numeric indices of all the remaining elements, because all subsequent elements of the array are shifted one position forward. The string array keys do not change.
If arr is empty or not an array, the function returns NULL.
After using this function, the array pointer is moved to the beginning.
Example of using array_shift() function:
$fruit = array_shift($stack);
print_r($stack);
?>
This example will output the following:
Array(
=> banana
=> apple
=> raspberry
)
and the $fruit variable will have the value "orange"
Function supported by PHP 4, PHP 5
array_unshift
Adds one or more values to the beginning of the array.
Syntax:
Int array_unshift(list arr, mixed var1 [,mixed var2, ...])
The array_unshift() function adds the passed var values to the beginning of the arr array. The order of new elements in the array is preserved. All digital indexes of the array will be changed so that it starts from zero. All string indexes of the array are unchanged.
The function returns the new number of elements in the array.
Example of using array_unshift() function:
array_unshift($queue, "apple", "raspberry");
?>
Now the $queue variable will have the following elements:
Array(
=> apple
=> raspberry
=> orange
=> banana
)
Function supported by PHP 4, PHP 5
array_unique
Removes duplicate values in an array.
Syntax:
Array array_unique(array arr)
The array_unique() function returns an array composed of all the unique values in the array arr along with their keys, by removing all duplicate values. The first key=>value pairs encountered are placed in the resulting array. The indexes are preserved.
An example of using the array_unique() function:
"green", "red", "b" =>
"green", "blue", "red");
print_r($result);
?>
The example will output the following:
Array(
[a] => green
=> red
=> blue
)
Example of using the array_unique() function: Comparing data types
$result = array_unique($input);
var_dump($result);
?>
The example will output the following:
Array(2) (
=> int(4)
=> string(1) "3"
}
Function supported by PHP 4 >= 4.0.1, PHP 5
array_chunk
The function splits the array into parts.
Syntax:
Array array_chunk(array arr, int size [, bool preserve_keys])
The array_chunk() function splits the original array arr into several arrays, the length of which is specified by the number size. If the dimension of the original array is not divisible exactly by the size of the parts, then the final array will have a smaller dimension.
The array_chunk() function returns a multidimensional array, the indices of which start from 0 to the number of resulting arrays, and the values are the arrays obtained as a result of splitting.
The optional preserve_keys parameter specifies whether the keys of the original array should be preserved or not. If this parameter is false (the default value), then the indices of the resulting arrays will be specified by numbers starting from zero. If the parameter is true, then the keys of the original array are preserved.
Example of using array_chunk() function:
$array = array("1st element",
"2nd element"
"3rd element"
"4th element"
"5th element");
print_r(array_chunk($array, 2));
print_r(array_chunk($array, 2, TRUE));
The example will output the following:
Array(
=> Array
=> 1st element
=> 2nd element
)
=> Array
=> 3rd element
=> 4th element
)
=> Array
=> 5th element
)
)
Array(
=> Array
=> 1st element
=> 2nd element
)
=> Array
=> 3rd element
=> 4th element
)
=> Array
=> 5th element
)
Function supported by PHP 4 >= 4.2.0, PHP 5
array_fill
The function fills the array with specific values.
Syntax:
Array array_fill(int start_index, int num, mixed value)
The array_fill() function returns an array containing the values specified in the value parameter of size num, starting with the element specified in the start_index parameter.
Example of using array_diff_uassoc():
print_r($a);
?>
The example will output the following:
Array(
=> banana
=> banana
=> banana
=> banana
=> banana
=> banana
)
Function supported by PHP 4 >= 4.2.0, PHP 5
array_filter
The function applies a filter to an array using a custom function.
Syntax:
Array array_filter(array input [, callback callback])
The array_filter() function returns an array that contains the values found in the input array, filtered according to the results of the user-defined callback function.
If the input array is an associative array, the indices are preserved in the resulting array.
Example of using array_filter() function:
return ($var % 2 == 1);
}
function even($var) (
return ($var % 2 == 0);
}
$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);
echo "Odd:n";
print_r(array_filter($array1, "odd"));
echo "Even:n";
t_r(array_filter($array2, "even"));
?>
The example will output the following:
Odd:Array(
[a] => 1
[c] => 3
[e] => 5
Even:Array(
=> 6
=> 8
=> 10
=> 12
)
It is worth noting that instead of the name of the filtering function, you can specify an array that contains a reference to the object and the name of the method.
It is also worth noting that when processing an array with the array_filter() function, it cannot be changed: adding, deleting elements or resetting the array, because this may lead to incorrect operation of the function.
Function supported by PHP 4 >= 4.0.6, PHP 5