Introduction to PHP – Array Functions Part 3

Guest Posts Paolo Nikko Nuñal

Have you ever found yourself being hassled with the fact of looping through an array and just getting their keys or values? We'll thankfully, you can easily get all the elements of an array values or keys with the use of two simple methods. Namely the arrayvalues and arraykeys. These two methods work wonders when it comes to getting the values or keys of an array that you wish.

Syntax:

array_keys([ARRAY]);


Array - The array you want to get the keys.

This is most useful if you are dealing with associative arrays and want to get the array_keys of a particular array. Here's an example.

Example:

<?php
    $account = array('Name' => 'John Blake', 'Age' => 23, 'Address' => 'New York City');
    $account_keys = array_keys($account);
    echo var_dump($account_keys);
?>


From the example above, the $accountkeys variable will store all the keys found on the $account arrays namely 'Name','Age' and 'Address' neatly packed inside an array since the arraykeys method returns an array.

On the other hand, the array_values method will return all the values found inside an array.

Syntax:

array_values([ARRAY]);


Array - The array you want to get the keys.

This is also useful if you plan on getting only the values without having to worry about or neglect the array keys that bind them.

Example:

<?php
    $account = array('Name' => 'John Blake', 'Age' => 23, 'Address' => 'New York City');
    $account_values= array_values($account);
    echo var_dump($account_values);
?>



From the results above, the $account_values variable will return all the values found on the $account array which is 'John Blake', '23', and 'New York City'.