PHP Array Library Functions

1)  array_keys :

    Syntax : array_keys ( array $array [, mixed $search_value = null [, bool $strict = false ]] )
    description : Return all the keys or a subset of the keys of an array

    Example #1 array_keys() example
    <?php
    $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));
    ?>



2) array_map   :

    Description : array_map — Applies the callback to the elements of the given arrays
    Syntax :   array array_map ( callable $callback , array $array1 [, array $... ] )

    Example #

    <?php
    function cube($n)
    {
        return($n * $n * $n);
    }

    $a = array(1, 2, 3, 4, 5);
    $b = array_map("cube", $a);
    print_r($b);
    ?>

    This makes $b have:
    Array
    (
        [0] => 1
        [1] => 8
        [2] => 27
        [3] => 64
        [4] => 125
    )

    Example #2 array_map() using a lambda function (as of PHP 5.3.0)
    <?php
    $func = function($value) {
        return $value * 2;
    };

    print_r(array_map($func, range(1, 5)));
    ?>
    Array
    (
        [0] => 2
        [1] => 4
        [2] => 6
        [3] => 8
        [4] => 10
    )
    Example #3 array_map() - using more arrays
    <?php
    function show_Spanish($n, $m)
    {
        return("The number $n is called $m in Spanish");
    }

    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 above example will output:
    // printout of $c
    Array
    (
        [0] => The number 1 is called uno in Spanish
        [1] => The number 2 is called dos in Spanish
        [2] => The number 3 is called tres in Spanish
        [3] => The number 4 is called cuatro in Spanish
        [4] => The number 5 is called cinco in Spanish
    )


3.....array_merge_recursive

syntax : array_merge_recursive ( array $array1 [, array $... ] )
description : Merge two or more arrays recursively


    Example #1 array_merge_recursive() example
    <?php
    $ar1 = array("color" => array("favorite" => "red"), 5);
    $ar2 = array(10, "color" => array("favorite" => "green", "blue"));
    $result = array_merge_recursive($ar1, $ar2);
    print_r($result);
    ?>

    The above example will output:
    Array
    (
        [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

        [0] => 5
        [1] => 10
    )

4...array_multisort

Description  : array_multisort — Sort multiple or multi-dimensional arrays
syntax : bool array_multisort ( array &$array1 [, mixed $array1_sort_order = SORT_ASC [, mixed $array1_sort_flags = SORT_REGULAR [, mixed $... ]]] )


Example #1 Sorting multiple arrays

<?php
$ar1 = array(10, 100, 100, 0);
$ar2 = array(1, 3, 2, 4);
array_multisort($ar1, $ar2);

var_dump($ar1);
var_dump($ar2);
?>

-----OutPut -----
array(4) {
  [0]=> int(0)
  [1]=> int(10)
  [2]=> int(100)
  [3]=> int(100)
}
array(4) {
  [0]=> int(4)
  [1]=> int(1)
  [2]=> int(2)
  [3]=> int(3)
}



Example #2 Sorting multi-dimensional array

<?php
$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)
  }
}

Example #3 Sorting database results
For this example, each element in the data array represents one row in a table. This type of dataset is typical of database records.
Example data:
volume | edition
-------+--------
    67 |       2
    86 |       1
    85 |       6
    98 |       2
    86 |       6
    67 |       7
The data as an array, called data. This would usually, for example, be obtained by looping with mysqli_fetch_assoc().
<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
?>
In this example, we will order by volume descending, edition ascending.
We have an array of rows, but array_multisort() requires an array of columns, so we use the below code to obtain the columns, then perform the sorting.
<?php
// Obtain a list of columns
foreach ($data as $key => $row) {
    $volume[$key]  = $row['volume'];
    $edition[$key] = $row['edition'];
}

// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>
The dataset is now sorted, and will look like this:
volume | edition
-------+--------
    98 |       2
    86 |       1
    86 |       6
    85 |       6
    67 |       2
    67 |       7


5.... array_pad

syntax :  array array_pad ( array $array , int $size , mixed $value )
description : Pad array to the specified length with a value

Example #1 array_pad() example
<?php
$input = array(12, 10, 9);

$result = array_pad($input, 5, 0);
// result is array(12, 10, 9, 0, 0)

$result = array_pad($input, -7, -1);
// result is array(-1, -1, -1, -1, 12, 10, 9)

$result = array_pad($input, 2, "noop");
// not padded
?>




6...array_pop

syntax : mixed array_pop ( array &$array ) 
description :  Pop the element off the end of array


Example #1 array_pop() example
<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
?>
After this, $stack will have only 3 elements:
Array
(
    [0] => orange
    [1] => banana
    [2] => apple
)

7... array_product

description : Calculate the product of values in an array
syntax : number array_product ( array $array )

Example #1 array_product() examples
<?php

$a = array(2, 4, 6, 8);
echo "product(a) = " . array_product($a) . "\n";
echo "product(array()) = " . array_product(array()) . "\n";

?>
The above example will output:
product(a) = 384
product(array()) = 1


8...array_push

Description : array_push — Push one or more elements onto the end of array
Syntax : int array_push ( array &$array , mixed $value1 [, mixed $... ] )

Example #1 array_push() example
<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>
The above example will output:
Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry

)


9....array_rand

Description : Pick one or more random entries out of an array
Syntax : array_rand ( array $array [, int $num = 1 ] )

Example #1 array_rand() 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";
?>


10...array_reduce

Description: array_reduce — Iteratively reduce the array to a single value using a callback function
Syntax : mixed array_reduce ( array $array , callable $callback [, mixed $initial = NULL ] )

Example #1 array_reduce() example
<?php
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
var_dump(array_reduce($x, "sum", "No data to reduce")); // string(17) "No data to reduce"
?>

11... array_replace

description :  Replaces elements from passed arrays into the first array
syntax :  array_replace ( array $array1 , array $array2 [, array $... ] )

Example #1 array_replace() example
<?php
$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);
?>
The above example will output:
Array
(
    [0] => grape
    [1] => banana
    [2] => apple
    [3] => raspberry
    [4] => cherry
)



12... array_reverse

description :  Return an array with elements in reverse order
syntax : array_reverse ( array $array [, bool $preserve_keys = false ] )

Example #1 array_reverse() example
<?php
$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);
?>
The above example will output:
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
)


13 ... array_search

syntax :  Searches the array for a given value and returns the first corresponding key if successful
description : mixed array_search ( mixed $needle , array $haystack [, bool $strict = false ] )


Example #1 array_search() example
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>


14...array_sum

syntax : number array_sum ( array $array )
description :  Calculate the sum of values in an array

Example #1 array_sum() examples
<?php
$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";
?>

The above example will output:
sum(a) = 20
sum(b) = 6.9


No comments:

Post a Comment

Pages