PHP Array Function

Here is the list of PHP array functions

sizeof () :- This function is used to count the items of the array. (count() is also used instead of this).

 

Example:

 

explode () :- This function is used to explode the string into an array.

Example:-

implode () :- This function is used to convert the array into a string.

Example:

Range () :- This function allows us to get the range of numbers such as 1,10 or 1,100 etc.. We need to specify two points. First one is starting point and second one is the end point. It returns all the numbers from the specified range.

Example:

<?php

//Define number range

$ran=range(1,10);

foreach($ran as $r){

echo $r;

}  ?>

 

min () max ():-  These functions are used to get the smallest and largest numbers in specified array.

Example:

<?php

//Define array

$data=array(1,10,4,6,7,9,2);

echo “Smallest number in this array is ” . min($data) . ” and largest number in this array is ” . max($data) . “.”;

?>

 

array_slice () :- This function is used to extract the particular segment from an array. It accepts 3 arguments. The original array, the starting index of array and the number of arrays to return. (If you want to slice the array from the end then use negative (-) symbol and the main thing is that we don’t use 0,1,2 index when counting from end but we use 1,2 index).

Example:

<?php

//Define array

$data=array(1,10,4,6,7,9,2);

$arr=array_slice($data,1,3);

print_r($arr);     //This is returned as an array

?>

 

array_unshift () :-  This function is used to add the element at the beginning of the array.

Example:

<?php

$a=array(“a”=>”red”,”b”=>”green”);

array_unshift($a,”blue”);

print_r($a);

?>

 

array_shift ():-   This function is used to remove the element from the beginning of the array.

Example:

<?php

$a=array(“a”=>”red”,”b”=>”green”,”c”=>”blue”);

echo array_shift($a);

print_r ($a);

?>

array_push ():-  This function is used to add the element at the end of the array.

<?php

$a=array(“red”,”green”);

array_push($a,”blue”,”yellow”);

print_r($a);

?>

 

array_pop ():-  This function is used to remove the element from the end of the array.

<?php

$a=array(“red”,”green”,”blue”);

array_pop($a);

print_r($a);

?>

 

array_unique():-  The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed.

Note: The returned array will keep the first array item’s key type.

Example:

<?php

$data=array(“a”,”x”,”s”,”z”,”a”,”z”);

$un=array_unique($data);

print_r($un);

?>

 

shuffle ():-  This function is used to shuffle (randomize) the array. (No need to make a new array data type).

Example1:

<?php

$my_array = array(“red”,”green”,”blue”,”yellow”,”purple”);

shuffle($my_array);

print_r($my_array);

?>

Example2:

<?php

$a=array(“red”,”green”,”blue”,”yellow”,”brown”);

$random_keys=array_rand($a,3);

echo $a[$random_keys[0]].”<br>”;

echo $a[$random_keys[1]].”<br>”;

echo $a[$random_keys[2]];

?>

Example3:

<?php

echo str_shuffle(“Hello World”);

?>

 

array_reverse ():-  This function is used to reverse the array. (Need to make a new array data type).

<?php

$a=array(“a”=>”Volvo”,”b”=>”BMW”,”c”=>”Toyota”);

print_r(array_reverse($a));

?>

in_array ():-  This function is used to search element in an array. It returns true if the specified element is exist in the array. It accepts 2 arguments – the element to search and the array data type. (If we want to search the keys then we have to use array_key_exists ()

Example1:

<?php

$data=array(“a”,”x”,”s”,”z”,”a”,”z”);

echo in_array(“a”,$data);

?>

Example2:

<?php

$people = array(“Peter”, “Joe”, “Glenn”, “Cleveland”);

if (in_array(“Glenn”, $people))  {

echo “Match found”;

} else  {

echo “Match not found”;

}

?>

array_key_exists (): – The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.

<?php

$a=array(“Volvo”=>”XC90″,”BMW”=>”X5”);

if (array_key_exists(“Volvo”,$a))  {

echo “Key exists!”;

}else  {

echo “Key does not exist!”;

} ?>

sort ():-  This function is used to sort the array. (If we want to reverse the sort sequence then we have to use rsort ()).

Example1:

<?php

$data=array(3,5,1,8,2,4,6,7);

sort($data);

foreach($data as $d){

echo $d . “\r\n”;

}

RESULT:

2

4

6

11

22

?>

 

asort ():-  This function is used to sort the associative array. Values are sorted here.  (If we want to reverse the sort sequence then we have to use arsort ())

ksort ():-  This function is used to sort the associative array. keys are sorted here.  (If we want to reverse the sort sequence then we have to use krsort ())

<?php

$age=array(“Peter”=>”35″,”Ben”=>”37″,”Joe”=>”43”);

ksort($age);

foreach($age as $x=>$x_value)   {

echo “Key=” . $x . “, Value=” . $x_value;

echo “<br>”;

}

?>

RESULT:

Key=Ben, Value=37

Key=Joe, Value=43

Key=Peter, Value=35

 

The ksort():-  function sorts an associative array in ascending order, according to the key.

Tip: Use the krsort() function to sort an associative array in descending order, according to the key.

Tip: Use the asort() function to sort an associative array in ascending order, according to the value.

 

array_intersect ():-  This function is used to find the common elements in two arrays. It accepts two argments (1st array and 2nd array).

Example:

<?php

$a1=array(“a”=>”red”,”b”=>”green”,”c”=>”blue”,”d”=>”yellow”);

$a2=array(“e”=>”red”,”f”=>”green”,”g”=>”blue”);

$result=array_intersect($a1,$a2);

print_r($result);

?>

Example2:

<?php

$a1=array(“a”=>”red”,”b”=>”green”,”c”=>”blue”,”d”=>”yellow”);

$a2=array(“e”=>”red”,”f”=>”black”,”g”=>”purple”);

$a3=array(“a”=>”red”,”b”=>”black”,”h”=>”yellow”);

$result=array_intersect($a1,$a2,$a3);

print_r($result);

?>

 

array_diff ():-  This function returns the values of the first array which are not exist in second. It accepts two argments (1st array and 2nd array).

Example1:

<?php

$a1=array(“a”=>”red”,”b”=>”green”,”c”=>”blue”,”d”=>”yellow”);

$a2=array(“e”=>”red”,”f”=>”green”,”g”=>”blue”);

$result=array_diff($a1,$a2);

print_r($result);

?>

Example2:

<?php

$a1=array(“a”=>”red”,”b”=>”green”,”c”=>”blue”,”d”=>”yellow”);

$a2=array(“e”=>”red”,”f”=>”black”,”g”=>”purple”);

$a3=array(“a”=>”red”,”b”=>”black”,”h”=>”yellow”);

$result=array_diff($a1,$a2,$a3);

print_r($result);

?>

Example2:

<?php

$a1=array(“a”=>”red”,”b”=>”green”,”c”=>”blue”,”d”=>”yellow”);

$a2=array(“e”=>”red”,”f”=>”green”,”g”=>”blue”);

$result=array_diff_assoc($a1,$a2);

print_r($result);

?>

 

The array_chunk():- function splits an array into chunks of new arrays.

<?php

$cars=array(“Volvo”,”BMW”,”Toyota”,”Honda”,”Mercedes”,”Opel”);

print_r(array_chunk($cars,2));

?>

 

The array_column():-  function returns the values from a single column in the input array.

<?php

// An array that represents a possible record set returned from a database

$a = array(

array(    ‘id’ => 5698,

‘first_name’ => ‘Peter’,

‘last_name’ => ‘Griffin’,

),

array(    ‘id’ => 4767,

‘first_name’ => ‘Ben’,

‘last_name’ => ‘Smith’,

),

array(    ‘id’ => 3809,

‘first_name’ => ‘Joe’,

‘last_name’ => ‘Doe’,  ));

$last_names = array_column($a, ‘last_name’);

print_r($last_names);

?>

<?php

// An array that represents a possible record set returned from a database

$a = array(

array(    ‘id’ => 5698,

‘first_name’ => ‘Peter’,

‘last_name’ => ‘Griffin’,

),

array(    ‘id’ => 4767,

‘first_name’ => ‘Ben’,

‘last_name’ => ‘Smith’,

),

array(    ‘id’ => 3809,

‘first_name’ => ‘Joe’,

‘last_name’ => ‘Doe’,

));

$last_names = array_column($a, ‘last_name’, ‘id’);

print_r($last_names);

?>

 

The array_combine():- function creates an array by using the elements from one “keys” array and one “values” array.

Note: Both arrays must have equal number of elements!

<?php

$fname=array(“Peter”,”Ben”,”Joe”);

$age=array(“35″,”37″,”43”);

$c=array_combine($fname,$age);

print_r($c);

?>

 

The array_count_values():- The array_count_value() function counts all the values of an array.

<?php

$a=array(“A”,”Cat”,”Dog”,”A”,”Dog”);

print_r(array_count_values($a));

?>

 

array_filter() :- The array_filter() function filters the values of an array using a callback function.

This function passes each value of the input array to the callback function. If the callback function returns true, the current value from input is returned into the result array. Array keys are preserved.

<?php

function odd($var) {

return($var & 1);

}

function even($var) {

return(!($var & 1));

}

$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”;

print_r(array_filter($array2, “even”));

?>

RESULT:

Odd: Array (

[a] => 1

[c] => 3

[e] => 5

)

Even: Array (

[0] => 6

[2] => 8

[4] => 10

[6] => 12

)

 

array_map() :- The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function.

Tip: You can assign one array to the function, or as many as you like.

 

<?php

function myfunction($v1,$v2)

{

if ($v1===$v2)

{  return “same”;  }

return “different”;

}

 

$a1=array(“Horse”,”Dog”,”Cat”);

$a2=array(“Cow”,”Dog”,”Rat”);

print_r(array_map(“myfunction”,$a1,$a2));

?>

 

<?php

function myfunction($v)

{

$v=strtoupper($v);

return $v;

}

 

$a=array(“Animal” => “horse”, “Type” => “mammal”);

print_r(array_map(“myfunction”,$a));

?>

 

Compact() :- The compact() function creates an array from variables and their values.

Note: Any strings that does not match variable names will be skipped.

<?php
$firstname = “Peter”;
$lastname = “Griffin”;
$age = “41”;

$result = compact(“firstname”, “lastname”, “age”);
print_r($result);

?>

 

array_sum() :- The array_sum() function returns the sum of all the values in the array.

<?php
$a=array(5,15,25);
echo array_sum($a);
?>

<?php
$a=array(“a”=>52.2,”b”=>13.7,”c”=>0.9);
echo array_sum($a);
?>

 

extract() :- The extract() function imports variables into the local symbol table from an array.

This function uses array keys as variable names and values as variable values. For each element it will create a variable in the current symbol table.

This function returns the number of variables extracted on success.

<?php
$a = “Original”;
$my_array = array(“a” => “Cat”,”b” => “Dog”, “c” => “Horse”);
extract($my_array);
echo “\$a = $a; \$b = $b; \$c = $c”;
?>

 

in_array() :- The in_array() function searches an array for a specific value.

Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.

<?php
$people = array(“Peter”, “Joe”, “Glenn”, “Cleveland”);

if (in_array(“Glenn”, $people))
{
echo “Match found”;

}else  {
echo “Match not found”;
}
?>

Related posts