Mr.Father Mr.Father - 4 months ago 9
PHP Question

How do I get all the values of an array without having to manually access to each key?

I would like to know how I can get all the values of an array without having to manually access to each key to then get the value.

That is, I have this arrangement.

$user = [ "Id" => 123, "Name" => "Dave", "Age" => 25, "Country" => "US"];


I want to get the values 123, "Dave," 25, "US".

Answer

PHP has a function that does exactly what you need, which is array_values Return all the values of an array.

// e.g.
$user = [
    "id"   => 123,
    "name" => "Dave",
    "age"  => 25,
    "country" => "US"
  ];

print_r(array_values($user));

Result

Array
    (
        [0] => 123
        [1] => Dave
        [2] => 25
        [3] => US
    )  

NOTE:

But beware of boolean values because if any value of the array is TRUE, array_values it will transform to 1 and if the value is FALSE will not return anything (it has the same behavior as the isset function)

Comments