Array

By ukmodak | March 31st 2024 10:36:23 AM | viewed 528 times

Arrays

PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple values of similar type in a single variable.

Advantage of PHP Array

Less Code: We don't need to define multiple variables.

Easy to traverse: By the help of single loop, we can traverse all the elements of an array.

Array Types

There are 3 types of array in PHP.

  • Indexed Array
  • Associative Array
  • Multidimensional Array
PHP Indexed Array

PHP index is represented by number which starts from 0. We can store number, string and object in the PHP array. All PHP array elements are assigned to an index number by default.

There are two ways to define indexed array:

1st way:
    $season=array("summer","winter","spring","autumn"); 

2nd way:
    $season[0]="summer";  
    $season[1]="winter";  
    $season[2]="spring";  
    $season[3]="autumn";   
iteration:
$season=array("summer","winter","spring","autumn");  
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";  

output:
Season are: summer, winter, spring and autumn 
Associative Array

We can associate name with each array elements in PHP using => symbol.

There are two ways to define associative array:

1st way:
    $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");  
	
2nd way:
    $salary["Sonoo"]="350000";  
    $salary["John"]="450000";  
    $salary["Kartik"]="200000";  
iteration:
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");    
echo "Sonoo salary: ".$salary["Sonoo"]."
"; echo "John salary: ".$salary["John"]."
"; echo "Kartik salary: ".$salary["Kartik"]."
"; output: Sonoo salary: 350000 John salary: 450000 Kartik salary: 200000
Multidimensional Array

PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an array. PHP multidimensional array can be represented in the form of matrix which is represented by row * column.

 $emp = array  
  (  
  array(1,"sonoo",400000),  
  array(2,"john",500000),  
  array(3,"rahul",300000)  
  );  

$emp = array  
  (  
  array(1,"sonoo",400000),  
  array(2,"john",500000),  
  array(3,"rahul",300000)  
  );  
  
for ($row = 0; $row < 3; $row++) {  
  for ($col = 0; $col < 3; $col++) {  
    echo $emp[$row][$col]."  ";  
  }  
  echo "
"; } Output: 1 sonoo 400000 2 john 500000 3 rahul 300000
Array Functions array_change_key_case — Changes the case of all keys in an array

array_change_key_case ( array $array [, int $case = CASE_LOWER ] ) : array

$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));

op:
Array
(
    [FIRST] => 1
    [SECOND] => 4
)
array_chunk — Split an array into chunks
array_chunk ( array $array , int $size [, bool $preserve_keys = FALSE ] ) : array
 
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));

op:
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
array_column — Return the values from a single column in the input array
array_column ( array $input , mixed $column_key [, mixed $index_key = NULL ] ) : array
$records = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ),
    array(
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
    ),
    array(
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
    )
);
 
$first_names = array_column($records, 'first_name');
print_r($first_names);
op:
Array
(
    [0] => John
    [1] => Sally
    [2] => Jane
    [3] => Peter
) 
array_combine — Creates an array by using one array for keys and another for its values
 array_combine ( array $keys , array $values ) : array
 $a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
op:
Array
(
    [green]  => avocado
    [red]    => apple
    [yellow] => banana
)
array_count_values — Counts all the values of an array
 array_count_values ( array $array ) : array
 $array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
op:
Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)
array_diff_assoc — Computes the difference of arrays with additional index check
 array_diff_assoc ( array $array1 , array $array2 [, array $... ] ) : array
 
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_assoc($array1, $array2);
print_r($result);

op:
Array
(
    [b] => brown
    [c] => blue
    [0] => red
)
array_diff_key — Computes the difference of arrays using keys for comparison
 array_diff_key ( array $array1 , array $array2 [, array $... ] ) : array
 
 $array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'yellow' => 7, 'cyan' => 8);

var_dump(array_diff_key($array1, $array2));

op:
array(3) {
  ["blue"]=>
  int(1)
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}
array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function
 array_diff_uassoc ( array $array1 , array $array2 [, array $... ], callable $key_compare_func ) : array
 
 function key_compare_func($a, $b)
{
    if ($a === $b) {
        return 0;
    }
    return ($a > $b)? 1:-1;
}

$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_uassoc($array1, $array2, "key_compare_func");
print_r($result);
op:
Array
(
    [b] => brown
    [c] => blue
    [0] => red
)
explain:
The "a" => "green" pair is present in both arrays and thus it is not in the output from the function. Unlike this, the pair 0 => "red" is in the output because in the second argument "red" has key which is 1. 
array_diff_ukey — Computes the difference of arrays using a callback function on the keys for comparison
 array_diff_ukey ( array $array1 , array $array2 [, array $... ], callable $key_compare_func ) : array
 
 function key_compare_func($key1, $key2)
{
    if ($key1 == $key2)
        return 0;
    else if ($key1 > $key2)
        return 1;
    else
        return -1;
}

$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_diff_ukey($array1, $array2, 'key_compare_func'));
op:
array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}
array_diff — Computes the difference of arrays
 array_diff ( array $array1 , array $array2 [, array $... ] ) : array
 
 $array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
op:
Array
(
    [1] => blue
)
array_fill_keys — Fill an array with values, specifying keys
array_fill_keys ( array $keys , mixed $value ) : array
$keys = array('foo', 5, 10, 'bar');
$a = array_fill_keys($keys, 'banana');
print_r($a);

op:
Array
(
    [foo] => banana
    [5] => banana
    [10] => banana
    [bar] => banana
)

array_fill — Fill an array with values
array_fill ( int $start_index , int $num , mixed $value ) : array
 
$a = array_fill(5, 6, 'banana');
$b = array_fill(-2, 4, 'pear');
print_r($a);
print_r($b);

op:
Array
(
    [5]  => banana
    [6]  => banana
    [7]  => banana
    [8]  => banana
    [9]  => banana
    [10] => banana
)
Array
(
    [-2] => pear
    [0] => pear
    [1] => pear
    [2] => pear
)
array_filter — Filters elements of an array using a callback function
 array_filter ( array $array [, callable $callback [, int $flag = 0 ]] ) : array
 
 function odd($var)
{
    // returns whether the input integer is odd
    return $var & 1;
}

function even($var)
{
    // returns whether the input integer is even
    return !($var & 1);
}

$array1 = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];
$array2 = [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"));

op:
Odd :
Array
(
    [a] => 1
    [c] => 3
    [e] => 5
)
Even:
Array
(
    [0] => 6
    [2] => 8
    [4] => 10
    [6] => 12
)


$array1 = ['a' =>'', 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];
print_r(array_filter($array1));

op;
Array
(
    [b] => 2
    [c] => 3
    [d] => 4
	[e] => 5
)
array_flip — Exchanges all keys with their associated values in an array

array_flip ( array $array ) : array
 
$input = array("a" => 1, "b" => 1, "c" => 2);
$flipped = array_flip($input);

print_r($flipped);

op:
Array
(
    [1] => b
    [2] => c
)

array_intersect_assoc — Computes the intersection of arrays with additional index check
 array_intersect_assoc ( array $array1 , array $array2 [, array $... ] ) : array
 
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "b" => "yellow", "blue", "red");
$result_array = array_intersect_assoc($array1, $array2);
print_r($result_array);

op:
Array
(
    [a] => green
)

array_intersect_key — Computes the intersection of arrays using keys for comparison

array_intersect_key ( array $array1 , array $array2 [, array $... ] ) : array
 
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_intersect_key($array1, $array2));

op:
array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
}

array_intersect_uassoc — Computes the intersection of arrays with additional index check, compares indexes by a callback function
 array_intersect_uassoc ( array $array1 , array $array2 [, array $... ], callable $key_compare_func ) : array
 
 $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_intersect_uassoc($array1, $array2, "strcasecmp"));

op:
Array
(
    [b] => brown
)
array_intersect_ukey — Computes the intersection of arrays using a callback function on the keys for comparison
array_intersect_ukey ( array $array1 , array $array2 [, array $... ], callable $key_compare_func ) : array
function key_compare_func($key1, $key2)
{
    if ($key1 == $key2)
        return 0;
    else if ($key1 > $key2)
        return 1;
    else
        return -1;
}

$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

var_dump(array_intersect_ukey($array1, $array2, 'key_compare_func'));

op:
array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
}

array_intersect — Computes the intersection of arrays
 array_intersect ( array $array1 , array $array2 [, array $... ] ) : array
 
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);

op:
Array
(
    [a] => green
    [0] => red
)
array_key_exists — Checks if the given key or index exists in the array
array_key_exists ( mixed $key , array $array ) : bool
 
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
}
 op:
 
array_key_first — Gets the first key of an array
 array_key_first ( array $array ) : mixed
 $array = ['a' => 1, 'b' => 2, 'c' => 3];

$firstKey = array_key_first($array);

var_dump($firstKey);
op:
string(1) "a"
array_key_last — Gets the last key of an array
 array_key_last ( array $array ) : mixed
array_keys — Return all the keys or a subset of the keys of an array
 array_keys ( array $array ) : array
 or
 array_keys ( array $array , mixed $search_value [, bool $strict = FALSE ] ) : array
 
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));

$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));

$array = array("color" => array("blue", "red", "green"),
               "size"  => array("small", "medium", "large"));
print_r(array_keys($array));

op:
Array
(
    [0] => 0
    [1] => color
)
Array
(
    [0] => 0
    [1] => 3
    [2] => 4
)
Array
(
    [0] => color
    [1] => size
)

 
array_map — Applies the callback to the elements of the given arrays
 array_map ( callable $callback , array $array1 [, array $... ] ) : array
 function cube($n)
{
    return ($n * $n * $n);
}

$a = [1, 2, 3, 4, 5];
$b = array_map('cube', $a);
print_r($b);
op:

Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)
array_merge_recursive — Merge one or more arrays recursively
array_merge_recursive ([ array $... ] ) : array
 
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);

op:
Array
(
    [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

    [0] => 5
    [1] => 10
)
 
array_merge — Merge one or more arrays
array_merge ([ array $... ] ) : array
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);

op:
Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)
array_multisort — Sort multiple or multi-dimensional arrays

array_multisort ( array &$array1 [, mixed $array1_sort_order = SORT_ASC [, mixed $array1_sort_flags = SORT_REGULAR [, mixed $... ]]] ) : bool
$ar = array(
       array("10", 11, 100, 100, "a"),
       array(   1,  2, "2",   3,   1)
      );
array_multisort($ar[0], SORT_ASC, SORT_STRING,$ar[1], SORT_NUMERIC, SORT_DESC);
var_dump($ar);

array(2) {
  [0]=> array(5) {
    [0]=> string(2) "10"
    [1]=> int(100)
    [2]=> int(100)
    [3]=> int(11)
    [4]=> string(1) "a"
  }
  [1]=> array(5) {
    [0]=> int(1)
    [1]=> int(3)
    [2]=> string(1) "2"
    [3]=> int(2)
    [4]=> int(1)
  }
}

array_pad — Pad array to the specified length with a value
 array_pad ( array $array , int $size , mixed $value ) : array
 $input = array(12, 10, 9);
 $result = array_pad($input, 5, 0);
 
 op:
 
 result is array(12, 10, 9, 0, 0)
 
array_pop — Pop the element off the end of array

$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);

op:
Array
(
    [0] => orange
    [1] => banana
    [2] => apple
)
 
 
array_product — Calculate the product of values in an array

 array_product ( array $array ) : number
 $a = array(2, 4, 6, 8);
 echo "product(a) = " . array_product($a) . "\n";
 echo "product(array()) = " . array_product(array()) . "\n";
 
 op:
 product(a) = 384
 product(array()) = 1
 
array_push — Push one or more elements onto the end of array
 array_push ( array &$array [, mixed $... ] ) : int
 
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);

op:
Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)

 
array_rand — Pick one or more random keys out of an array
array_rand ( array $array [, int $num = 1 ] ) : mixed
 
$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";
 
array_reduce — Iteratively reduce the array to a single value using a callback function

array_reduce ( array $array , callable $callback [, mixed $initial = NULL ] ) : mixed
function sum($carry, $item)
{
    $carry += $item;
    return $carry;
}

function product($carry, $item)
{
    $carry *= $item;
    return $carry;
}

$a = array(1, 2, 3, 4, 5);
$x = array();

var_dump(array_reduce($a, "sum")); // int(15)
var_dump(array_reduce($a, "product", 10)); // int(1200), because: 10*1*2*3*4*5

array_replace_recursive — Replaces elements from passed arrays into the first array recursively
 array_replace_recursive ( array $array1 [, array $... ] ) : array
 
 
$base = array('citrus' => array( "orange") , 'berries' => array("blackberry", "raspberry"), );
$replacements = array('citrus' => array('pineapple'), 'berries' => array('blueberry'));

$basket = array_replace_recursive($base, $replacements);
print_r($basket);

$basket = array_replace($base, $replacements);
print_r($basket);

op:
Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
            [1] => raspberry
        )

)
Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
        )

)
array_replace — Replaces elements from passed arrays into the first array
 array_replace ( array $array1 [, array $... ] ) : array
 
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");

$basket = array_replace($base, $replacements, $replacements2);
print_r($basket);

op:
Array
(
    [0] => grape
    [1] => banana
    [2] => apple
    [3] => raspberry
    [4] => cherry
)

array_reverse — Return an array with elements in reverse order
 array_reverse ( array $array [, bool $preserve_keys = FALSE ] ) : array
 
$input  = array("php", 4.0, array("green", "red"));
$reversed = array_reverse($input);
$preserved = array_reverse($input, true);

print_r($input);
print_r($reversed);
print_r($preserved);

op:
Array
(
    [0] => php
    [1] => 4
    [2] => Array
        (
            [0] => green
            [1] => red
        )

)
Array
(
    [0] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [2] => php
)
Array
(
    [2] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [0] => php
)

array_search — Searches the array for a given value and returns the first corresponding key if successful
 array_search ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : mixed
 $array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
array_shift — Shift an element off the beginning of array
 array_shift ( array &$array ) : mixed
 
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);

op:
Array
(
    [0] => banana
    [1] => apple
    [2] => raspberry
)

array_slice — Extract a slice of the array
 array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = FALSE ]] ) : array
 
 $input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2);      // returns "c", "d", and "e"
$output = array_slice($input, -2, 1);  // returns "d"
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"

// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));

op:
Array
(
    [0] => c
    [1] => d
)
Array
(
    [2] => c
    [3] => d
)
array_splice — Remove a portion of the array and replace it with something else
 array_splice ( array &$input , int $offset [, int $length = count($input) [, mixed $replacement = array() ]] ) : array
 
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
var_dump($input);

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
var_dump($input);

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
var_dump($input);

$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
var_dump($input);

op:
array(2) {
  [0]=>
  string(3) "red"
  [1]=>
  string(5) "green"
}
array(2) {
  [0]=>
  string(3) "red"
  [1]=>
  string(6) "yellow"
}
array(2) {
  [0]=>
  string(3) "red"
  [1]=>
  string(6) "orange"
}
array(5) {
  [0]=>
  string(3) "red"
  [1]=>
  string(5) "green"
  [2]=>
  string(4) "blue"
  [3]=>
  string(5) "black"
  [4]=>
  string(6) "maroon"
}


array_sum — Calculate the sum of values in an array
 array_sum ( array $array ) : number
 
 $a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";

op:
sum(a) = 20
sum(b) = 6.9
array_udiff_assoc — Computes the difference of arrays with additional index check, compares data by a callback function
 array_udiff_assoc ( array $array1 , array $array2 [, array $... ], callable $value_compare_func ) : array
 
 class cr {
    private $priv_member;
    function cr($val)
    {
        $this->priv_member = $val;
    }

    static function comp_func_cr($a, $b)
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }
}

$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff_assoc($a, $b, array("cr", "comp_func_cr"));
print_r($result);

op:
Array
(
    [0.1] => cr Object
        (
            [priv_member:private] => 9
        )

    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )
)
array_udiff_uassoc — Computes the difference of arrays with additional index check, compares data and indexes by a callback function
 array_udiff_uassoc ( array $array1 , array $array2 [, array $... ], callable $value_compare_func , callable $key_compare_func ) : array
 
 class cr {
    private $priv_member;
    function cr($val)
    {
        $this->priv_member = $val;
    }

    static function comp_func_cr($a, $b)
    {
        if ($a->priv_member === $b->priv_member) return 0;
        return ($a->priv_member > $b->priv_member)? 1:-1;
    }

    static function comp_func_key($a, $b)
    {
        if ($a === $b) return 0;
        return ($a > $b)? 1:-1;
    }
}
$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff_uassoc($a, $b, array("cr", "comp_func_cr"), array("cr", "comp_func_key"));
print_r($result);

op:
Array
(
    [0.1] => cr Object
        (
            [priv_member:private] => 9
        )

    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )
)
array_udiff — Computes the difference of arrays by using a callback function for data comparison
 array_udiff ( array $array1 , array $array2 [, array $... ], callable $value_compare_func ) : array
 // Arrays to compare
$array1 = array(new stdclass, new stdclass,
                new stdclass, new stdclass,
               );

$array2 = array(
                new stdclass, new stdclass,
               );

// Set some properties for each object
$array1[0]->width = 11; $array1[0]->height = 3;
$array1[1]->width = 7;  $array1[1]->height = 1;
$array1[2]->width = 2;  $array1[2]->height = 9;
$array1[3]->width = 5;  $array1[3]->height = 7;

$array2[0]->width = 7;  $array2[0]->height = 5;
$array2[1]->width = 9;  $array2[1]->height = 2;

function compare_by_area($a, $b) {
    $areaA = $a->width * $a->height;
    $areaB = $b->width * $b->height;
    
    if ($areaA < $areaB) {
        return -1;
    } elseif ($areaA > $areaB) {
        return 1;
    } else {
        return 0;
    }
}

print_r(array_udiff($array1, $array2, 'compare_by_area'));

op:
Array
(
    [0] => stdClass Object
        (
            [width] => 11
            [height] => 3
        )

    [1] => stdClass Object
        (
            [width] => 7
            [height] => 1
        )

)
array_uintersect_assoc — Computes the intersection of arrays with additional index check, compares data by a callback function
 array_uintersect_assoc ( array $array1 , array $array2 [, array $... ], callable $value_compare_func ) : array
 
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect_assoc($array1, $array2, "strcasecmp"));
op:
Array
(
    [a] => green
)
array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions
array_uintersect_uassoc ( array $array1 , array $array2 [, array $... ], callable $value_compare_func , callable $key_compare_func ) : array
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect_uassoc($array1, $array2, "strcasecmp", "strcasecmp"));

Array
(
    [a] => green
    [b] => brown
)
array_uintersect — Computes the intersection of arrays, compares data by a callback function
array_uintersect ( array $array1 , array $array2 [, array $... ], callable $value_compare_func ) : array
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect($array1, $array2, "strcasecmp"));
op:
Array
(
    [a] => green
    [b] => brown
    [0] => red
)
array_unique — Removes duplicate values from an array
array_unique ( array $array [, int $sort_flags = SORT_STRING ] ) : array

$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);

Array
(
    [a] => green
    [0] => red
    [1] => blue
)
array_unshift — Prepend one or more elements to the beginning of an array
array_unshift ( array &$array [, mixed $... ] ) : int
$queue = array("orange", "banana");
array_unshift($queue, "apple", "raspberry");
print_r($queue);
op:
Array
(
    [0] => apple
    [1] => raspberry
    [2] => orange
    [3] => banana
)
array_values — Return all the values of an array
array_values ( array $array ) : array
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
op:
Array
(
    [0] => XL
    [1] => gold
)
array_walk_recursive — Apply a user function recursively to every member of an array
array_walk_recursive ( array &$array , callable $callback [, mixed $userdata = NULL ] ) : bool
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');

function test_print($item, $key)
{
    echo "$key holds $item\n";
}

array_walk_recursive($fruits, 'test_print');
op:
a holds apple
b holds banana
sour holds lemon
array_walk — Apply a user supplied function to every member of an array
 array_walk ( array &$array , callable $callback [, mixed $userdata = NULL ] ) : bool
 $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

function test_alter(&$item1, $key, $prefix)
{
    $item1 = "$prefix: $item1";
}

function test_print($item2, $key)
{
    echo "$key. $item2
\n"; } echo "Before ...:\n"; array_walk($fruits, 'test_print'); array_walk($fruits, 'test_alter', 'fruit'); echo "... and after:\n"; array_walk($fruits, 'test_print'); op: Before ...: d. lemon a. orange b. banana c. apple ... and after: d. fruit: lemon a. fruit: orange b. fruit: banana c. fruit: apple
array — Create an array
array ([ mixed $... ] ) : array
$array = array(1, 1, 1, 1,  1, 8 => 1,  4 => 1, 19, 3 => 13);
print_r($array);

op:

Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 13
    [4] => 1
    [8] => 1
    [9] => 19
)

arsort — Sort an array in reverse order and maintain index association
 arsort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) : bool
 $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
arsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}

op:
a = orange
d = lemon
b = banana
c = apple
compact — Create array containing variables and their values
 compact ( mixed $varname1 [, mixed $... ] ) : array
 $city  = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";

$location_vars = array("city", "state");

$result = compact("event", $location_vars);
print_r($result);

op:
Array
(
    [event] => SIGGRAPH
    [city] => San Francisco
    [state] => CA
)
count — Count all elements in an array, or something in an object
count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] ) : int
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
var_dump(count($a));

op:
int(3)
current — Return the current element in an array
 current ( array $array ) : mixed
 $transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = current($transport); // $mode = 'bike';
$mode = prev($transport);    // $mode = 'foot';
$mode = end($transport);     // $mode = 'plane';
$mode = current($transport); // $mode = 'plane';
op:
$arr = array();
var_dump(current($arr)); // bool(false)
each — Return the current key and value pair from an array and advance the array cursor


each — Return the current key and value pair from an array and advance the array cursor
 each ( array &$array ) : array
 
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each($foo);
print_r($bar);

op:
Array
(
    [1] => bob
    [value] => bob
    [0] => 0
    [key] => 0
)

end — Set the internal pointer of an array to its last element
end ( array &$array ) : mixed
$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry
extract — Import variables into the current symbol table from an array
 extract ( array &$array [, int $flags = EXTR_OVERWRITE [, string $prefix = NULL ]] ) : int
 $size = "large";
$var_array = array("color" => "blue",
                   "size"  => "medium",
                   "shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");

echo "$color, $size, $shape, $wddx_size\n";

op:
blue, large, sphere, medium
in_array — Checks if a value exists in an array
 in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) : bool
 $os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
    echo "Got Irix";
}

op:
Got Irix
key_exists — Alias of array_key_exists()
 array_key_exists ( mixed $key , array $array ) : bool
 
 $search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
}

op:

key — Fetch a key from an array
 key ( array $array ) : mixed
 $array = array(
    'fruit1' => 'apple',
    'fruit2' => 'orange',
    'fruit3' => 'grape',
    'fruit4' => 'apple',
    'fruit5' => 'apple');

// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
    if ($fruit_name == 'apple') {
        echo key($array).'
'; } next($array); } op: fruit1
fruit4
fruit5
krsort — Sort an array by key in reverse order
 krsort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) : bool
 $fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}

op:
d = lemon
c = apple
b = banana
a = orange
ksort — Sort an array by key
 ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) : bool
 
 $fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}

op:
a = orange
b = banana
c = apple
d = lemon
list — Assign variables as if they were an array
 $info = array('coffee', 'brown', 'caffeine');

// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";

list($a, list($b, $c)) = array(1, array(2, 3));

var_dump($a, $b, $c);

op:

int(1)
int(2)
int(3)



natcasesort — Sort an array using a case insensitive "natural order" algorithm
 natcasesort ( array &$array ) : bool
 
 $array1 = $array2 = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');

sort($array1);
echo "Standard sorting\n";
print_r($array1);

natcasesort($array2);
echo "\nNatural order sorting (case-insensitive)\n";
print_r($array2);

op:
Standard sorting
Array
(
    [0] => IMG0.png
    [1] => IMG3.png
    [2] => img1.png
    [3] => img10.png
    [4] => img12.png
    [5] => img2.png
)

Natural order sorting (case-insensitive)
Array
(
    [0] => IMG0.png
    [4] => img1.png
    [3] => img2.png
    [5] => IMG3.png
    [2] => img10.png
    [1] => img12.png
)

natsort — Sort an array using a "natural order" algorithm
 natsort ( array &$array ) : bool
 
$array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png");

asort($array1);
echo "Standard sorting\n";
print_r($array1);

natsort($array2);
echo "\nNatural order sorting\n";
print_r($array2);

 op:
 
 Standard sorting
Array
(
    [3] => img1.png
    [1] => img10.png
    [0] => img12.png
    [2] => img2.png
)

Natural order sorting
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)



next — Advance the internal pointer of an array
 next ( array &$array ) : mixed
 $transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = next($transport);    // $mode = 'car';
$mode = prev($transport);    // $mode = 'bike';
$mode = end($transport);     // $mode = 'plane';
pos — Alias of current() prev — Rewind the internal array pointer
 prev ( array &$array ) : mixed
 $transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport);    // $mode = 'bike';
$mode = next($transport);    // $mode = 'car';
$mode = prev($transport);    // $mode = 'bike';
$mode = end($transport);     // $mode = 'plane';
range — Create an array containing a range of elements
 range ( mixed $start , mixed $end [, number $step = 1 ] ) : array
 
 foreach (range('c', 'a') as $letter) {
    echo $letter;
}
op:

// array('c', 'b', 'a');

reset — Set the internal pointer of an array to its first element
 reset ( array &$array ) : mixed
 
 $array = array('step one', 'step two', 'step three', 'step four');

// by default, the pointer is on the first element
echo current($array) . "
\n"; // "step one" // skip two steps next($array); next($array); echo current($array) . "
\n"; // "step three" // reset pointer, start again on step one reset($array); echo current($array) . "
\n"; // "step one"
rsort — Sort an array in reverse order
 rsort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) : bool
 
 $fruits = array("lemon", "orange", "banana", "apple");
rsort($fruits);
foreach ($fruits as $key => $val) {
    echo "$key = $val\n";
}
op:

0 = orange
1 = lemon
2 = banana
3 = apple
shuffle — Shuffle an array
 shuffle ( array &$array ) : bool
 
$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
    echo "$number ";
}
 
sizeof — Alias of count() sort — Sort an array
 sort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) : bool
 $fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
    echo "fruits[" . $key . "] = " . $val . "\n";
}

op:
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange
uasort — Sort an array with a user-defined comparison function and maintain index association
 uasort ( array &$array , callable $value_compare_func ) : bool
 // Comparison function
function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

// Array to be sorted
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4);
print_r($array);

// Sort and print the resulting array
uasort($array, 'cmp');
print_r($array);

op:
Array
(
    [a] => 4
    [b] => 8
    [c] => -1
    [d] => -9
    [e] => 2
    [f] => 5
    [g] => 3
    [h] => -4
)
Array
(
    [d] => -9
    [h] => -4
    [c] => -1
    [e] => 2
    [g] => 3
    [a] => 4
    [f] => 5
    [b] => 8
)

uksort — Sort an array by keys using a user-defined comparison function
 uksort ( array &$array , callable $key_compare_func ) : bool
 
 function cmp($a, $b)
{
    $a = preg_replace('@^(a|an|the) @', '', $a);
    $b = preg_replace('@^(a|an|the) @', '', $b);
    return strcasecmp($a, $b);
}

$a = array("John" => 1, "the Earth" => 2, "an apple" => 3, "a banana" => 4);

uksort($a, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $value\n";
}

op:
an apple: 3
a banana: 4
the Earth: 2
John: 1
usort — Sort an array by values using a user-defined comparison function
 usort ( array &$array , callable $value_compare_func ) : bool
 
 function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

usort($a, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $value\n";
}

op:
0: 1
1: 2
2: 3
3: 5
4: 6
bONEandALL
Visitor

Total : 27273

Today :9

Today Visit Country :

  • United States
  • Sweden
  • Singapore
  • Russia