Friday 26 June 2015

Useful PHP Array Functions You Need To Know!

Array Utility Type Functions

First off, we’ll look at some basic utility type functions for working with arrays in PHP. Things like checking to see if a variable is an array, looking inside of an array, and so on.
1. is_array(mixed $var)

You might want to know if a variable is an array. If you created it yourself, you’ll know, but what if this is a value that came from a remote api, or database, or some other means. You’ll need to check that variable to see what it is and this is how to do it. The function signature states it can take a mixed variable. That means, just pass in any old variable you want no matter what it is. If it is an array, the function will return true, otherwise it will return false.

<?php

$dynamic = array(
    'number' => 7,
    'live' => 'House',
    'drive' => 'Car',
    array(
        'mow' => 'grass',
        array(
            'tractor' => 'John Deere',
            'tractor2' => 'Kubota',
            'tractor3' => 'New Holland'
        ),
        'landscape' => 'mulch'
    )
);

$one = is_array($dynamic);

$two = is_array($dynamic['number']);

$three = is_array($dynamic[0]);

echo $one ? 'The $dynamic variable is an array<br>' : 'The $dynamic variable is not an array<br>';
echo $two ? 'The "number" key of the $dynamic variable is an array<br>' : 'The "number" key of the $dynamic variable is not an array<br>';
echo $three ? 'The 0 index of the $dynamic variable is an array<br>' : 'The 0 index of the $dynamic variable is not an array<br>';

?>
<?php

$dynamic = array(
    'number' => 7,
    'live' => 'House',
    'drive' => 'Car',
    array(
        'mow' => 'grass',
        array(
            'tractor' => 'John Deere',
            'tractor2' => 'Kubota',
            'tractor3' => 'New Holland'
        ),
        'landscape' => 'mulch'
    )
);

$one = is_array($dynamic);

$two = is_array($dynamic['number']);

$three = is_array($dynamic[0]);

echo $one ? 'The $dynamic variable is an array<br>' : 'The $dynamic variable is not an array<br>';
echo $two ? 'The "number" key of the $dynamic variable is an array<br>' : 'The "number" key of the $dynamic variable is not an array<br>';
echo $three ? 'The 0 index of the $dynamic variable is an array<br>' : 'The 0 index of the $dynamic variable is not an array<br>';

?>

The $dynamic variable is an array
The “number” key of the $dynamic variable is not an array
The 0 index of the $dynamic variable is an array

Cool! By using our array of things we created earlier, we can check to confirm what data types are stored in that array. We have numbers, strings, and arrays, and this code shows how to check for those scenarios.
2. in_array( mixed $needle , array $haystack [, bool $strict = FALSE ] )

Sometimes there will be instances where an array is quite large containing maybe hundreds or thousands of values. You might need to check if a certain value is in an array and with this function you can do that. The function signature requires you to pass in a needle to search for, an array as the haystack, and optionally a strict flag with will perform a value and type sensitive search. Watch this function in action now.

<?php
$veggies = array("Spinach", "Corn", "Carrots", "Tomatoes");
if (in_array("Tomatoes", $veggies)) {
    echo "The best Tomatoes make the best Red Sauce!<br>";
}
if (in_array("Snickers Bar", $veggies)) {
    echo "Eating a Snickers is Great.";
}

$dynamic = array(
    'number' => 7,
    'live' => 'House',
    'drive' => 'Car',
    array(
        'mow' => 'grass',
        array(
            'tractor' => 'John Deere',
            'tractor2' => 'Kubota',
            'tractor3' => 'New Holland'
        ),
        'landscape' => 'mulch'
    )
);

$tractor = $dynamic[0][0]['tractor'];

if (in_array('grass', $dynamic[0])) {
    echo "Time to take a spin on the $tractor and get the grass cut!<br>";
}
?>
   
<?php
$veggies = array("Spinach", "Corn", "Carrots", "Tomatoes");
if (in_array("Tomatoes", $veggies)) {
    echo "The best Tomatoes make the best Red Sauce!<br>";
}
if (in_array("Snickers Bar", $veggies)) {
    echo "Eating a Snickers is Great.";
}

$dynamic = array(
    'number' => 7,
    'live' => 'House',
    'drive' => 'Car',
    array(
        'mow' => 'grass',
        array(
            'tractor' => 'John Deere',
            'tractor2' => 'Kubota',
            'tractor3' => 'New Holland'
        ),
        'landscape' => 'mulch'
    )
);

$tractor = $dynamic[0][0]['tractor'];

if (in_array('grass', $dynamic[0])) {
    echo "Time to take a spin on the $tractor and get the grass cut!<br>";
}
?>

The best Tomatoes make the best Red Sauce!
Time to take a spin on the John Deere and get the grass cut!
3. array_unique( array $array [, int $sort_flags = SORT_STRING ] )

This is a fantastic function to use and it’s use case is to get rid of any duplicate values in the array you provide to it. Say you run a regular expression match on a piece of text and you get back hundreds of matches in the results all stored in an array. Well, we don’t need duplicates, so we can simply apply the array_unique function to get what we want. In this example we’ll take an array of strings that has many duplicates and screen them out.

<?php
$array = array (
        'Ten Steps To a Better You',
        'Ten Steps To a Better You',
        'Ten Steps To a Better You',
        'Eating Spiniach - The Pros Show You How',
        'Eating Spiniach - The Pros Show You How',
        'Falling in Love with Arrays',
        'Falling in Love with Arrays',
        'Stock Market Secrects Jim Cramer Will Not Share',
        'Uplifting News by ZeroHege',
        'Uplifting News by ZeroHege'
);
$unique = array_unique ( $array );

foreach($unique as $u) {
    echo $u.'<br>';
}
?>
<?php
$array = array (
        'Ten Steps To a Better You',
        'Ten Steps To a Better You',
        'Ten Steps To a Better You',
        'Eating Spiniach - The Pros Show You How',
        'Eating Spiniach - The Pros Show You How',
        'Falling in Love with Arrays',
        'Falling in Love with Arrays',
        'Stock Market Secrects Jim Cramer Will Not Share',
        'Uplifting News by ZeroHege',
        'Uplifting News by ZeroHege'
);
$unique = array_unique ( $array );

foreach($unique as $u) {
    echo $u.'<br>';
}
?>

Ten Steps To a Better You
Eating Spiniach – The Pros Show You How
Falling in Love with Arrays
Stock Market Secrects Jim Cramer Will Not Share
Uplifting News by ZeroHege
4. array_search( mixed $needle , array $haystack [, bool $strict = false ] )

The array_search function is very handy for finding a value in an array and determining where it lives. That is to say, this function provides to you the index or key for the value you are searching for. Let’s see how it works here.

<?php
$array = array (
        'How to build a website',
        'Design with Twitter Bootstrap',
        'Handle the backend with PHP',
        'Eat Veggies for good health',
        'The answers to all of your questions',
        'Racing in the Nascar Series'
);

$index = array_search('The answers to all of your questions', $array);

echo "The answers to all of your questions is located at index $index of the array."
?>
<?php
$array = array (
        'How to build a website',
        'Design with Twitter Bootstrap',
        'Handle the backend with PHP',
        'Eat Veggies for good health',
        'The answers to all of your questions',
        'Racing in the Nascar Series'
);

$index = array_search('The answers to all of your questions', $array);

echo "The answers to all of your questions is located at index $index of the array."
?>

The answers to all of your questions is located at index 4 of the array.
5. array_reverse( array $array [, bool $preserve_keys = false ] )

It’s really easy to take an array and reverse it’s order. With this function you also have the option to keep the keys in tact or not. Let’s test it out.

<?php
$array = array (
        'How to build a website',
        'Design with Twitter Bootstrap',
        'Handle the backend with PHP',
        'Eat Veggies for good health',
        'The answers to all of your questions',
        'Racing in the Nascar Series'
);

$array1 = array_reverse($array);
$array2 = array_reverse($array, true);

foreach($array1 as $a => $b) {
    echo $a.' - '.$b.'<br>';
}

echo '<br>';

foreach($array2 as $a => $b) {
    echo $a.' - '.$b.'<br>';
}
?>
<?php
$array = array (
        'How to build a website',
        'Design with Twitter Bootstrap',
        'Handle the backend with PHP',
        'Eat Veggies for good health',
        'The answers to all of your questions',
        'Racing in the Nascar Series'
);

$array1 = array_reverse($array);
$array2 = array_reverse($array, true);

foreach($array1 as $a => $b) {
    echo $a.' - '.$b.'<br>';
}

echo '<br>';

foreach($array2 as $a => $b) {
    echo $a.' - '.$b.'<br>';
}
?>

0 – Racing in the Nascar Series
1 – The answers to all of your questions
2 – Eat Veggies for good health
3 – Handle the backend with PHP
4 – Design with Twitter Bootstrap
5 – How to build a website

5 – Racing in the Nascar Series
4 – The answers to all of your questions
3 – Eat Veggies for good health
2 – Handle the backend with PHP
1 – Design with Twitter Bootstrap
0 – How to build a website
6. array_map( callable $callback , array $array1 [, array $… ] )

The array_map function is pretty useful in that you can run a function on every single element in the array. You need to define a function, then that function name is given to the array_map function as the first parameter, and the second parameter is the array to iterate over. Let’s turn our array of mixed case strings into all lowercase.

<?php
$array = array (
        'How to build a website',
        'Design with Twitter Bootstrap',
        'Handle the backend with PHP',
        'Eat Veggies for good health',
        'The answers to all of your questions',
        'Racing in the Nascar Series'
);

function lower($array) { 
    return strtolower($array);
}

$lc = array_map ( 'lower', $array );
foreach($lc as $l){
    echo $l.'<br>';
}
?>
<?php
$array = array (
        'How to build a website',
        'Design with Twitter Bootstrap',
        'Handle the backend with PHP',
        'Eat Veggies for good health',
        'The answers to all of your questions',
        'Racing in the Nascar Series'
);

function lower($array) { 
    return strtolower($array);
}

$lc = array_map ( 'lower', $array );
foreach($lc as $l){
    echo $l.'<br>';
}
?>

how to build a website
design with twitter bootstrap
handle the backend with php
eat veggies for good health
the answers to all of your questions
racing in the nascar series
7. array_diff( array $array1 , array $array2 [, array $… ] )

The array_diff function compares one or more arrays and provides only the values present in array one, that are not in any other arrays. Let’s see how it works.

<?php
$arrayone = array (
        'Google',
        'Microsoft',
        'Apple',
        'Adobe',
        'Cisco',
        'Juniper',
        'Lenovo',
        'Samsung',
        'Red Hat'
);

$arraytwo = array (
        'Google',
        'Microsoft',
        'Apple',
        'Adobe',
        'Cisco',
        'Juniper',
        'Lenovo',
        'Samsung'
);

$diff = array_diff ( $arrayone, $arraytwo );

print_r($diff);
?>
<?php
$arrayone = array (
        'Google',
        'Microsoft',
        'Apple',
        'Adobe',
        'Cisco',
        'Juniper',
        'Lenovo',
        'Samsung',
        'Red Hat'
);

$arraytwo = array (
        'Google',
        'Microsoft',
        'Apple',
        'Adobe',
        'Cisco',
        'Juniper',
        'Lenovo',
        'Samsung'
);

$diff = array_diff ( $arrayone, $arraytwo );

print_r($diff);
?>
Array ( [8] => Red Hat )
Array Counting Functions

Now that we have some useful utility type array functions covered, let’s look at some array functions related to counting values or dealing with numbers. We can count the number of things in an array, return the maximum or minimum value, and all kinds of other useful hacks. Let’s see how.
8. count( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )

The best way to see how this great function works is to simply put it into action!

<?php
$dynamic = array(
    'number' => 7,
    'live' => 'House',
    'drive' => 'Car',
    array(
        'mow' => 'grass',
        array(
            'tractor' => 'John Deere',
            'tractor2' => 'Kubota',
            'tractor3' => 'New Holland'
        ),
        'landscape' => 'mulch'
    )
);

$veggies = array("Spinach", "Corn", "Carrots", "Tomatoes", "Cucumbers");

$tractor = $dynamic[0][0];

$tech = array (
        'Google',
        'Microsoft',
        'Apple',
        'Adobe',
        'Cisco',
        'Juniper',
        'Lenovo',
        'Samsung',
        'Red Hat'
);


$v1 = count($dynamic);
$v2 = count($veggies);
$v3 = count($tractor);
$v4 = count($tech);

echo "We have $v1 items in the dynamic array, $v2 vegetables, $v3 tractors, and $v4 tech companies.  Thanks for using the count function.";
?>
<?php
$dynamic = array(
    'number' => 7,
    'live' => 'House',
    'drive' => 'Car',
    array(
        'mow' => 'grass',
        array(
            'tractor' => 'John Deere',
            'tractor2' => 'Kubota',
            'tractor3' => 'New Holland'
        ),
        'landscape' => 'mulch'
    )
);

$veggies = array("Spinach", "Corn", "Carrots", "Tomatoes", "Cucumbers");

$tractor = $dynamic[0][0];

$tech = array (
        'Google',
        'Microsoft',
        'Apple',
        'Adobe',
        'Cisco',
        'Juniper',
        'Lenovo',
        'Samsung',
        'Red Hat'
);


$v1 = count($dynamic);
$v2 = count($veggies);
$v3 = count($tractor);
$v4 = count($tech);

echo "We have $v1 items in the dynamic array, $v2 vegetables, $v3 tractors, and $v4 tech companies.  Thanks for using the count function.";
?>

We have 4 items in the dynamic array, 5 vegetables, 3 tractors, and 9 tech companies. Thanks for using the count function.
9. max( array $values )

Finds the max value in the array.
10. min( array $values )

Finds the min value in the array.
11. array_rand( array $array [, int $num = 1 ] )

Returns a random value from an array. We’ll test all three of these functions in one shot.
<?php

$numbers = array('12', '234651', '234', '41', '89', '196583', '1', '86', '3', '5', '9');

echo max($numbers).'<br>';
echo min($numbers).'<br>';
$rand = array_rand($numbers);
echo $rand;
?>
   
<?php

$numbers = array('12', '234651', '234', '41', '89', '196583', '1', '86', '3', '5', '9');

echo max($numbers).'<br>';
echo min($numbers).'<br>';
$rand = array_rand($numbers);
echo $rand;

?>
array_count_values( array $array )

This is an incredible array function you can make use of. What it does is take an array with many values, and then counts the number of times each value occurs in the array. It does this by turning the original array’s values into keys in the new array, and assigns a number count for how many times that value occurred originally as the new value. An example is in order. Say we had a huge array of stock ticker symbols. In this array there are tons of entries that occur many many times. We’ll use this function to count how many times each ticker is present.

<?php

$stocktickers = array('aapl', 'aapl', 'aapl', 'goog', 'goog', 'yhoo', 'fslr', 'msft', 'csco', 'csco');

$values = array_count_values($stocktickers);
print_r($values);

?>

   
<?php

$stocktickers = array('aapl', 'aapl', 'aapl', 'goog', 'goog', 'yhoo', 'fslr', 'msft', 'csco', 'csco');

$values = array_count_values($stocktickers);
print_r($values);

?>

Array ( [aapl] => 3 [goog] => 2 [yhoo] => 1 [fslr] => 1 [msft] => 1 [csco] => 2 )
Array Sorting Functions

There are a plethora of functions to do all kinds of sorts on your arrays. We’ll take a quick look at the common ones now. What we can do is take a few of our arrays so far and apply the various sorts to them. The behavior will be different based on the types that are in the array and so on. The best case scenario is you simply test the function in question before trying to use it in your program. There is a special point to notice about these following four functions. Take note that the array passed in begins with an & in the function signature. What this means is that these functions are destructive. That is to say, they directly modify the array in memory, they do not create a copy of the original. This is something to keep in mind when sorting arrays.
13. sort( array &$array [, int $sort_flags = SORT_REGULAR ] )
14. asort( array &$array [, int $sort_flags = SORT_REGULAR ] )
15. rsort( array &$array [, int $sort_flags = SORT_REGULAR ] )
16. arsort( array &$array [, int $sort_flags = SORT_REGULAR ] )

<?php
$mixed = array(
    'number' => 7,
    'live' => 'House',
    'drive' => 'Car',
    array(
        'mow' => 'grass',
        array(
            'tractor' => 'John Deere',
            'tractor2' => 'Kubota',
            'tractor3' => 'New Holland'
        ),
        'landscape' => 'mulch'
    )
);

$veggies = array("Spinach", "Corn", "Carrots", "Tomatoes", "Cucumbers");

$tech = array (
        'Google',
        'Microsoft',
        'Apple',
        'Adobe',
        'Cisco',
        'Juniper',
        'Lenovo',
        'Samsung',
        'Red Hat'
);
$stocktickers = array('aapl', 'aapl', 'aapl', 'goog', 'goog', 'yhoo', 'fslr', 'msft', 'csco', 'csco');

$numbers = array('12', '234651', '234', '41', '89', '196583', '1', '86', '3', '5', '9');

echo '<pre>';

sort($mixed);
sort($veggies);
sort($stocktickers);
sort($numbers);

print_r($mixed);
print_r($veggies);
print_r($stocktickers);
print_r($numbers);
?>
   
<?php
$mixed = array(
    'number' => 7,
    'live' => 'House',
    'drive' => 'Car',
    array(
        'mow' => 'grass',
        array(
            'tractor' => 'John Deere',
            'tractor2' => 'Kubota',
            'tractor3' => 'New Holland'
        ),
        'landscape' => 'mulch'
    )
);

$veggies = array("Spinach", "Corn", "Carrots", "Tomatoes", "Cucumbers");

$tech = array (
        'Google',
        'Microsoft',
        'Apple',
        'Adobe',
        'Cisco',
        'Juniper',
        'Lenovo',
        'Samsung',
        'Red Hat'
);
$stocktickers = array('aapl', 'aapl', 'aapl', 'goog', 'goog', 'yhoo', 'fslr', 'msft', 'csco', 'csco');

$numbers = array('12', '234651', '234', '41', '89', '196583', '1', '86', '3', '5', '9');

echo '<pre>';

sort($mixed);
sort($veggies);
sort($stocktickers);
sort($numbers);

print_r($mixed);
print_r($veggies);
print_r($stocktickers);
print_r($numbers);

?>
//  sort($mixed);
Array
(
    [0] => Car
    [1] => House
    [2] => 7
    [3] => Array
        (
            [mow] => grass
            [0] => Array
                (
                    [tractor] => John Deere
                    [tractor2] => Kubota
                    [tractor3] => New Holland
                )

            [landscape] => mulch
        )

)
//  sort($veggies);
Array
(
    [0] => Carrots
    [1] => Corn
    [2] => Cucumbers
    [3] => Spinach
    [4] => Tomatoes
)

//  sort($stocktickers);
Array
(
    [0] => aapl
    [1] => aapl
    [2] => aapl
    [3] => csco
    [4] => csco
    [5] => fslr
    [6] => goog
    [7] => goog
    [8] => msft
    [9] => yhoo
)
//  sort($numbers);
Array
(
    [0] => 1
    [1] => 3
    [2] => 5
    [3] => 9
    [4] => 12
    [5] => 41
    [6] => 86
    [7] => 89
    [8] => 234
    [9] => 196583
    [10] => 234651
)

   
//  sort($mixed);
Array
(
    [0] => Car
    [1] => House
    [2] => 7
    [3] => Array
        (
            [mow] => grass
            [0] => Array
                (
                    [tractor] => John Deere
                    [tractor2] => Kubota
                    [tractor3] => New Holland
                )

            [landscape] => mulch
        )

)
//  sort($veggies);
Array
(
    [0] => Carrots
    [1] => Corn
    [2] => Cucumbers
    [3] => Spinach
    [4] => Tomatoes
)

//  sort($stocktickers);
Array
(
    [0] => aapl
    [1] => aapl
    [2] => aapl
    [3] => csco
    [4] => csco
    [5] => fslr
    [6] => goog
    [7] => goog
    [8] => msft
    [9] => yhoo
)
//  sort($numbers);
Array
(
    [0] => 1
    [1] => 3
    [2] => 5
    [3] => 9
    [4] => 12
    [5] => 41
    [6] => 86
    [7] => 89
    [8] => 234
    [9] => 196583
    [10] => 234651
)


//  asort($mixed);
Array
(
    [drive] => Car
    [live] => House
    [number] => 7
    [0] => Array
        (
            [mow] => grass
            [0] => Array
                (
                    [tractor] => John Deere
                    [tractor2] => Kubota
                    [tractor3] => New Holland
                )

            [landscape] => mulch
        )

)
//  asort($veggies);
Array
(
    [2] => Carrots
    [1] => Corn
    [4] => Cucumbers
    [0] => Spinach
    [3] => Tomatoes
)
//  asort($stocktickers);
Array
(
    [0] => aapl
    [2] => aapl
    [1] => aapl
    [8] => csco
    [9] => csco
    [6] => fslr
    [4] => goog
    [3] => goog
    [7] => msft
    [5] => yhoo
)
//  asort($numbers);
Array
(
    [6] => 1
    [8] => 3
    [9] => 5
    [10] => 9
    [0] => 12
    [3] => 41
    [7] => 86
    [4] => 89
    [2] => 234
    [5] => 196583
    [1] => 234651
)

   
//  asort($mixed);
Array
(
    [drive] => Car
    [live] => House
    [number] => 7
    [0] => Array
        (
            [mow] => grass
            [0] => Array
                (
                    [tractor] => John Deere
                    [tractor2] => Kubota
                    [tractor3] => New Holland
                )

            [landscape] => mulch
        )

)
//  asort($veggies);
Array
(
    [2] => Carrots
    [1] => Corn
    [4] => Cucumbers
    [0] => Spinach
    [3] => Tomatoes
)
//  asort($stocktickers);
Array
(
    [0] => aapl
    [2] => aapl
    [1] => aapl
    [8] => csco
    [9] => csco
    [6] => fslr
    [4] => goog
    [3] => goog
    [7] => msft
    [5] => yhoo
)
//  asort($numbers);
Array
(
    [6] => 1
    [8] => 3
    [9] => 5
    [10] => 9
    [0] => 12
    [3] => 41
    [7] => 86
    [4] => 89
    [2] => 234
    [5] => 196583
    [1] => 234651
)


//  rsort($mixed);
Array
(
    [0] => Array
        (
            [mow] => grass
            [0] => Array
                (
                    [tractor] => John Deere
                    [tractor2] => Kubota
                    [tractor3] => New Holland
                )

            [landscape] => mulch
        )

    [1] => 7
    [2] => House
    [3] => Car
)
//  rsort($veggies);
Array
(
    [0] => Tomatoes
    [1] => Spinach
    [2] => Cucumbers
    [3] => Corn
    [4] => Carrots
)
//  rsort($stocktickers);
Array
(
    [0] => yhoo
    [1] => msft
    [2] => goog
    [3] => goog
    [4] => fslr
    [5] => csco
    [6] => csco
    [7] => aapl
    [8] => aapl
    [9] => aapl
)
//  rsort($numbers);
Array
(
    [0] => 234651
    [1] => 196583
    [2] => 234
    [3] => 89
    [4] => 86
    [5] => 41
    [6] => 12
    [7] => 9
    [8] => 5
    [9] => 3
    [10] => 1
)

//  rsort($mixed);
Array
(
    [0] => Array
        (
            [mow] => grass
            [0] => Array
                (
                    [tractor] => John Deere
                    [tractor2] => Kubota
                    [tractor3] => New Holland
                )

            [landscape] => mulch
        )

    [1] => 7
    [2] => House
    [3] => Car
)
//  rsort($veggies);
Array
(
    [0] => Tomatoes
    [1] => Spinach
    [2] => Cucumbers
    [3] => Corn
    [4] => Carrots
)
//  rsort($stocktickers);
Array
(
    [0] => yhoo
    [1] => msft
    [2] => goog
    [3] => goog
    [4] => fslr
    [5] => csco
    [6] => csco
    [7] => aapl
    [8] => aapl
    [9] => aapl
)
//  rsort($numbers);
Array
(
    [0] => 234651
    [1] => 196583
    [2] => 234
    [3] => 89
    [4] => 86
    [5] => 41
    [6] => 12
    [7] => 9
    [8] => 5
    [9] => 3
    [10] => 1
)


//  arsort($mixed);
Array
(
    [0] => Array
        (
            [mow] => grass
            [0] => Array
                (
                    [tractor] => John Deere
                    [tractor2] => Kubota
                    [tractor3] => New Holland
                )

            [landscape] => mulch
        )

    [number] => 7
    [live] => House
    [drive] => Car
)
//  arsort($veggies);
Array
(
    [3] => Tomatoes
    [0] => Spinach
    [4] => Cucumbers
    [1] => Corn
    [2] => Carrots
)
//  arsort($stocktickers);
Array
(
    [5] => yhoo
    [7] => msft
    [3] => goog
    [4] => goog
    [6] => fslr
    [9] => csco
    [8] => csco
    [1] => aapl
    [0] => aapl
    [2] => aapl
)
//  arsort($numbers);
Array
(
    [1] => 234651
    [5] => 196583
    [2] => 234
    [4] => 89
    [7] => 86
    [3] => 41
    [0] => 12
    [10] => 9
    [9] => 5
    [8] => 3
    [6] => 1
)

   
//  arsort($mixed);
Array
(
    [0] => Array
        (
            [mow] => grass
            [0] => Array
                (
                    [tractor] => John Deere
                    [tractor2] => Kubota
                    [tractor3] => New Holland
                )

            [landscape] => mulch
        )

    [number] => 7
    [live] => House
    [drive] => Car
)
//  arsort($veggies);
Array
(
    [3] => Tomatoes
    [0] => Spinach
    [4] => Cucumbers
    [1] => Corn
    [2] => Carrots
)
//  arsort($stocktickers);
Array
(
    [5] => yhoo
    [7] => msft
    [3] => goog
    [4] => goog
    [6] => fslr
    [9] => csco
    [8] => csco
    [1] => aapl
    [0] => aapl
    [2] => aapl
)
//  arsort($numbers);
Array
(
    [1] => 234651
    [5] => 196583
    [2] => 234
    [4] => 89
    [7] => 86
    [3] => 41
    [0] => 12
    [10] => 9
    [9] => 5
    [8] => 3
    [6] => 1
)

Converting Between Arrays and Strings

Converting between arrays and strings happens all the time. As such, PHP provides the implode and explode functions. They are quite easy to use and work just like their names imply. implode takes in an array and glues it together as one big string while explode takes in a string and delimiter and explodes that string into pieces based on the delimiter provided. Let’s check them out.
17. implode( string $glue , array $pieces )
18. explode( string $delimiter , string $string [, int $limit ] )

<?php

$glue = '*';

$pieces = array('Yaba', 'Daba', 'Doo', 'Who', 'Loves', 'You', '?');

echo implode($glue, $pieces);

?>

<?php

$glue = '*';

$pieces = array('Yaba', 'Daba', 'Doo', 'Who', 'Loves', 'You', '?');

echo implode($glue, $pieces);

?>

Yaba*Daba*Doo*Who*Loves*You*?

<?php

$glue = '*';

$pieces = array('Yaba', 'Daba', 'Doo', 'Who', 'Loves', 'You', '?');

$string = implode($glue, $pieces);

$array = explode('*', $string);

print_r($array);

?>

<?php

$glue = '*';

$pieces = array('Yaba', 'Daba', 'Doo', 'Who', 'Loves', 'You', '?');

$string = implode($glue, $pieces);

$array = explode('*', $string);

print_r($array);

?>


Array
(
    [0] => Yaba
    [1] => Daba
    [2] => Doo
    [3] => Who
    [4] => Loves
    [5] => You
    [6] => ?
)

Array
(
    [0] => Yaba
    [1] => Daba
    [2] => Doo
    [3] => Who
    [4] => Loves
    [5] => You
    [6] => ?
)

General Manipulation Functions

Last up we have a handful of general array manipulation functions that you are most likely to come across in your day to day programming. Let’s take a look at a few of these now.
19. array_key_exists( mixed $key , array $array )

We can check to see if a certain key exists in our array with this handy function. This is how to use it.

<?php

$array = array(
    'phone' => 'iPhone',
    'laptop' => 'Carbon X1',
    'car' => 'Tesla'
    );

$true = array_key_exists('laptop', $array);

echo 'Do you have a laptop?  ';

if($true) {
    echo 'Why yes, yes I do in fact.';
} else {
    echo 'No I use my tablet instead';
}

?>

<?php

$array = array(
    'phone' => 'iPhone',
    'laptop' => 'Carbon X1',
    'car' => 'Tesla'
    );

$true = array_key_exists('laptop', $array);

echo 'Do you have a laptop?  ';

if($true) {
    echo 'Why yes, yes I do in fact.';
} else {
    echo 'No I use my tablet instead';
}

?>

Do you have a laptop? Why yes, yes I do in fact.
20. array_keys( array $array [, mixed $search_value [, bool $strict = false ]] )

This function allows us to quickly see all of the keys of the array, but not the values. Here is how to do that.

<?php

$array = array(
    'phone' => 'iPhone',
    'laptop' => 'Carbon X1',
    'car' => 'Tesla'
    );

$keys = array_keys($array);

print_r($keys);

?>

<?php

$array = array(
    'phone' => 'iPhone',
    'laptop' => 'Carbon X1',
    'car' => 'Tesla'
    );

$keys = array_keys($array);

print_r($keys);

?>

Array
(
    [0] => phone
    [1] => laptop
    [2] => car
)

   
Array
(
    [0] => phone
    [1] => laptop
    [2] => car
)
21. array_values( array $array )

What about if we want to see all the values of the array instead of the keys? How can we accomplish that? Just like this!

<?php

$array = array(
    'phone' => 'iPhone',
    'laptop' => 'Carbon X1',
    'car' => 'Tesla'
    );

$values = array_values($array);

print_r($values);

?>

<?php

$array = array(
    'phone' => 'iPhone',
    'laptop' => 'Carbon X1',
    'car' => 'Tesla'
    );

$values = array_values($array);

print_r($values);

?>

Array
(
    [0] => iPhone
    [1] => Carbon X1
    [2] => Tesla
)

   
Array
(
    [0] => iPhone
    [1] => Carbon X1
    [2] => Tesla
)
22. array_push( array &$array , mixed $value1 [, mixed $… ] )

Now we come into using the push, pop, unshift, and shift array functions. These deal with adding things to the end of the array, removing things from the end of the array, adding things to the begging of an array, and removing things from the beginning of an array respectively. Let’s see them in action.

<?php

$array = array(
    'Apples',
    'Blueberries',
    'Pumpkins',
    'Corn'
    );

array_push($array, 'Watermelons');
echo '<pre>';
print_r($array);

?>

<?php

$array = array(
    'Apples',
    'Blueberries',
    'Pumpkins',
    'Corn'
    );

array_push($array, 'Watermelons');
echo '<pre>';
print_r($array);

?>

Array
(
    [0] => Apples
    [1] => Blueberries
    [2] => Pumpkins
    [3] => Corn
    [4] => Watermelons
)

Array
(
    [0] => Apples
    [1] => Blueberries
    [2] => Pumpkins
    [3] => Corn
    [4] => Watermelons
)
23. array_pop( array &$array )

<?php

$array = array(
    'Apples',
    'Blueberries',
    'Pumpkins',
    'Corn',
    'Watermelons'
    );

$yummy = array_pop($array);

echo "Would you like some delicious $yummy?";

?>

<?php

$array = array(
    'Apples',
    'Blueberries',
    'Pumpkins',
    'Corn',
    'Watermelons'
    );

$yummy = array_pop($array);

echo "Would you like some delicious $yummy?";

?>

Would you like some delicious Watermelons?
24. array_unshift( array &$array , mixed $value1 [, mixed $… ] )

<?php

$array = array(
    'Apples',
    'Blueberries',
    'Pumpkins',
    'Corn',
    'Watermelons'
    );

array_unshift($array, 'Apple Pies');

echo '<pre>';

print_r($array);

?>

   
<?php

$array = array(
    'Apples',
    'Blueberries',
    'Pumpkins',
    'Corn',
    'Watermelons'
    );

array_unshift($array, 'Apple Pies');

echo '<pre>';

print_r($array);

?>

Array
(
    [0] => Apple Pies
    [1] => Apples
    [2] => Blueberries
    [3] => Pumpkins
    [4] => Corn
    [5] => Watermelons
)

Array
(
    [0] => Apple Pies
    [1] => Apples
    [2] => Blueberries
    [3] => Pumpkins
    [4] => Corn
    [5] => Watermelons
)
25. array_shift( array &$array )

<?php

$array = array(
    'Apple Pies',
    'Apples',
    'Blueberries',
    'Pumpkins',
    'Corn',
    'Watermelons'
    );

$eat = array_shift($array);

echo "Let us eat some $eat together!";

?>

<?php

$array = array(
    'Apple Pies',
    'Apples',
    'Blueberries',
    'Pumpkins',
    'Corn',
    'Watermelons'
    );

$eat = array_shift($array);

echo "Let us eat some $eat together!";

?>

Let us eat some Apple Pies together!
26. array_splice( array &$input , int $offset [, int $length [, mixed $replacement = array() ]] )

<?php

$array = array(
    'Apple Pies',
    'Apples',
    'Blueberries',
    'Pumpkins',
    'Corn',
    'Watermelons'
    );

array_splice($array, 3, 1, 'Chocolates');

print_r($array);

?>

<?php

$array = array(
    'Apple Pies',
    'Apples',
    'Blueberries',
    'Pumpkins',
    'Corn',
    'Watermelons'
    );

array_splice($array, 3, 1, 'Chocolates');

print_r($array);

?>

Array
(
    [0] => Apple Pies
    [1] => Apples
    [2] => Blueberries
    [3] => Chocolates
    [4] => Corn
    [5] => Watermelons
)

Array
(
    [0] => Apple Pies
    [1] => Apples
    [2] => Blueberries
    [3] => Chocolates
    [4] => Corn
    [5] => Watermelons
)
27. array_merge( array $array1 [, array $… ] )

<?php

$eats = array(
    'Apple Pies',
    'Apples',
    'Blueberries',
    'Pumpkins',
    'Corn',
    'Watermelons'
    );
   
$drinks = array(
    'Water',
    'Apple Juice',
    'Craft Beer',
    'Iced Tea',
    'Coffee'
    );

$dinner = array_merge($eats, $drinks);

echo '<pre>';

print_r($dinner);

?>

   
<?php

$eats = array(
    'Apple Pies',
    'Apples',
    'Blueberries',
    'Pumpkins',
    'Corn',
    'Watermelons'
    );
   
$drinks = array(
    'Water',
    'Apple Juice',
    'Craft Beer',
    'Iced Tea',
    'Coffee'
    );

$dinner = array_merge($eats, $drinks);

echo '<pre>';

print_r($dinner);

?>

Array
(
    [0] => Apple Pies
    [1] => Apples
    [2] => Blueberries
    [3] => Pumpkins
    [4] => Corn
    [5] => Watermelons
    [6] => Water
    [7] => Apple Juice
    [8] => Craft Beer
    [9] => Iced Tea
    [10] => Coffee
)

Array
(
    [0] => Apple Pies
    [1] => Apples
    [2] => Blueberries
    [3] => Pumpkins
    [4] => Corn
    [5] => Watermelons
    [6] => Water
    [7] => Apple Juice
    [8] => Craft Beer
    [9] => Iced Tea
    [10] => Coffee
)

0 comments:

Post a Comment