Arrays Functions
Arrays Functions
$lastname = "Griffin";
$age = "41";
$result = compact("firstname", "lastname" ,"age");
print_r($result);
1.The in_array();
The in_array() this function is used to check if a value exists in a
given array…
The in_array() function returns TRUE if the value is found in the
array, or FALSE otherwise.
And it is case sensitive if strings are used.
Syntax: in_array(search, array, type)
Example:
<?php>
$cars=["benz","bmw","audi","bugatti"];
if (in_array("Benzi", $cars)) {
echo "Got Benz";
}
if (in_array("bmw", $cars)) {
echo "got bmw";
}
<?>
output : got bmw;
2) array_diff(): The array_diff() is an inbuilt function in PHP that is
used to calculate the difference between two or more arrays.
Parameters: Arrays;
Return value: The element(s) present in the first array but not in
other arrays
Example
<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red","pink");
print_r($result);
//this will print “blue” because it is not present in array2
?>
Output:
Array ( [1] => blue )
3) Array_sum function sums up numeric values of an array. Either
float or Int.
For example:
$a = array(2,4,6,8);
$b = array(
"a"=>1.2,
"b"=>2.3,
"c"=>3.4
);
echo "Sum(a)= ". array_sum($a); // It will print 20
echo "<br>";
echo "Sum(b)= ". array_sum($b); //It will print 6.9
Output:
Sum(a)= 20
Sum(b)= 6.9
4. array_push(): inserts one or more elements to the end of an
array. You may insert one element or as many as you like.
Example:
<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);//apple and raspberry will be added to the array at
the last indices.
?>
output
Array ( [0] => orange [1] => banana [2] => apple [3] => raspberry )
5. sort(): Sorts/Arranges the elements of the array in an ascending
numerical order (if they are numbers) and it arranges the elements
of that array in an ascending alphabetical
order (if those elements are strings).
<?php
$arr = array(21, 19, 20, 16, 25);
sort($arr);
print_r($arr);
?>
output:
Array ( [0] => 16 [1] => 19 [2] => 20 [3] => 21 [4] => 25 )
6. Array_merge(): this array function merges/combines two or more
arrays.
Example:
<?php
$array1 = array(2,3,4,5,6);
$array2 = array(2,3,4,5,6,”key” => "data");
$result = array_merge($array1, $array2);
?>
Result:
Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 [5] => 2 [6] => 3 [7]
=> 4 [8] => 5 [9] => 6 [key] => data )
NB: If we are merging associative arrays with some elements which
have the same keys in key value pairs, the array_merge function
will only consider the last element.
7) array_reverse: Returns an array with elements in reverse order
Example:
$arr = array("a","b","c","d","e");
print_r ($arr);
echo "<br>";
print_r (array_reverse($arr));
Output:
Array ( [0] => a [1] => b [2] => c [3] => d [4] => e )
Array ( [0] => e [1] => d [2] => c [3] => b [4] => a )
You can specify an optional second argument which will be either
true or false. If true, the element’s indexes will be preserved false is
the default and it means the element’s indexes will not be
preserved.
Description
Parameters
array
The array.
Return Values
Returns an indexed array of values.
Examples
Example #1 array_values() example
<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
?>
The above example will output:
Array
(
[0] => XL
[1] => gold
)
12.array_unique
This function checks whether there are no duplicates in the array
passed in and goes on to remove the found duplicated from the
array.
Example:
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
The above will return:
Array
(
[a] => green
[0] => red
[1] => blue
)
This function can also take an optional second parameter“sort
flags”
● SORT_STRING - Default. Compare items as strings
● SORT_REGULAR - Compare items normally (don't change types)
● SORT_NUMERIC - Compare items numerically
● SORT_LOCALE_STRING - Compare items as strings, based on current
locale
Output
Key=Gizo, Value=11
Key=Saad, Value=13
Key=Joe, Value=23
14.arsort: This function sorts an associative array in descending
order or reverse alphabetical order, according to the value.
Example1:
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
arsort($age);
foreach($age as $key=>$value){
echo "Name: ".$key. " and Age:".$value;
echo"<br>";
}
?>
Output:
Name: Joe and Age:43
Name: Ben and Age:37
Name: Peter and Age:35
Example2:
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c"
=> "apple");
arsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val".”<br>”;
}
?>
Output:
a = orange
d = lemon
b = banana
c = apple
Output:
Key=Peter, Value=35
Key=Joe, Value=43
Key=Ben, Value=37
17.array_replace
Array_replace is a function that replaces the values of the first array
with values of the second array.As it is replacing, it must work with
two or more arrays.
For associative arrays, if keys of arrays are the same, values are
changed but if a key is only existent in one array,it is left as it is.
If multiple arrays are used, values from later arrays will overwrite
the previous ones.
Syntax.
array_replace($array1, $array2);
Example
<!DOCTYPE html>
<html>
<body>
<?php
$a1=array("a"=>"red","b"=>"green");
$a2=array("a"=>"orange","b"=>"burgundy");
print_r(array_replace($a1,$a2));
?>
</body>
</html>
18.array_search
It searches for a value in an array and returns it’s corresponding
key.
ex:
$colors=array("First-color"=>"red","Second-color"=
>"green","Third-color"=>"blue");
echo array_search("red",$colors);
19.current
The current() function returns the value of the current element in
an array.
Every array has an internal pointer to its "current" element, which
is initialized to the first element inserted into the array.
It takes one parameter which is the array.
FOR EXAMPLE:
$score = [1,2,3,4];
Echo current($score);
The output:
1
NOTE This function does not move the arrays internal pointer
20.next
Description.
next() behaves like current(), with one difference. It advances the
internal array pointer one place forward before returning the
element value. That means it returns the next array value and
advances the internal array pointer by one.
Return type
next() behaves like current(), with one difference. It advances the
internal array pointer one place forward before returning the
element value. That means it returns the next array value and
advances the internal array pointer by one.
21.prev
Prev rewinds the array pointer. Prev() behaves just like next() except
that it rewinds the internal array pointer in one place instead of
advancing it.
Forexample:
echo prev($people);
The output:
Peter
Joe
Peter
22.end
end() advances the array’s internal pointer to the last element and
returns its value.
Returns the value of the last element or false if the array is empty.
$scores(23,44,65,33);
echo end($scores); //Output = 33
23.each
Return the current element key and value in an array with four elements, and
move the internal pointer or the cursor forward, First two elements returned (1
and value ) are for the element value, and other two elements ( 0 and key ) are
for the element key.
Example:
<?php
$prod = array("Electronics", "Footwear", "Toys");
print_r (each($prod));
?>
Result:
Array (
[1] => Electronics
[value] => Electronics
[0] => 0
[key] => 0
)
24.array_rand
Picks one or more random entries out of an array, and returns the
key (or keys) of the random entries.
When picking only one entry, array_rand() returns the key for a
random entry. Otherwise, an array of keys for the random entries is
returned. This is done so that random keys can be picked from the
array as well as random values. If multiple keys are returned, they
will be returned in the order they were present in the original array.
Trying to pick more elements than there are in the array will result
in an E_WARNING level error, and NULL will be returned.
Example :
<?php
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>
Output :
It will output the values of the randomly selected keys at index 0
and 1.
25.array_pop:
array_pop() — Pops (removes) the last element of array, shortening the array by one
element.
Ex:
<?php
$fruit = array_pop($stack);
print_r($stack);
?>
Output:
Array
26.array_key_exists
array_key_exists() — Checks if the given key or index exists in the
array
Parameters: key, array
Return values: true, false
Ex:
<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>
27. Array_product
Array_product function accepts an array as a parameter and
returns the product of elements in the array.
N.B: If the array has string elements the product will be 0.
E.g:$a=[2,6];
echo array_product($a);//returns 12
$a=[2,6,"product"];
echo array_product($a);//returns 0
28.count
29.array_shift():
array_shift() shifts the first value of the array off and returns it,
shortening the array by one element and moving everything down.
Example:
<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
?>
Output
Array([0] => banana [1] => apple [2] => raspberry)
NB: and orange will be assigned to $fruit
30. Array_slice
array_slice is a function that selects specific positions in an array
and returns those selected values;
syntax:
array_slice($arrayname, starting position, length, preserve or do
not preserve indexes(boolean))
example:
$array = [1,2,3,4,5,6]; ||
print_r(array_slice($array,2,1,true));|| => this will return Array (
[2] => 3 ).
31.array_intersect
● The array_intersect() function compares the values of two (or
more) arrays and returns the array of matches or intersection.
32.array_keys
The array_keys function returns the array containing the keys for that array.
It takes three parameters:
● array (The name of the array and it is required).
● Value (You can specify a value, then only the keys with this value
are returned. It is optional)
● strict(It is optional and goes with value. True:Returns the keys with the specified
value, depending on type: the number 5 is not the same as the string "5".False:
Default value. Not depending on type, the number 5 is the same as
the string "5")
This function is used to create an array of variables using string variable names.
While compacting.
Example: