What is the difference between the array_keys and array_values functions in PHP?

Hey there, fellow PHP enthusiasts! If you’re working with arrays in PHP, then you’ve probably come across the array_keys and array_values functions. While they may seem similar at first glance, these two functions serve different purposes and it’s important to understand the difference between them.

The array_keys function returns an array of all the keys in an array. For example, if you have an associative array such as:

$fruits = array("a" => "apple", "b" => "banana", "c" => "cherry");

Using the array_keys function on this array would return an array containing the keys “a”, “b”, and “c”.

print_r(array_keys($fruits));

The result would be:

Array
(
    [0] => a
    [1] => b
    [2] => c
)

On the other hand, the array_values function returns an array of all the values in an array. Using the same example as before:

print_r(array_values($fruits));

The result would be:

Array
(
    [0] => apple
    [1] => banana
    [2] => cherry
)

So to summarize, if you’re looking to extract the keys of an array, you would use array_keys. And if you’re looking to extract the values, you would use array_values.

I hope this clears things up and helps you in your PHP programming journey!

Follow us on Twitter: Hacktube5

Leave a Reply