How to get keys and values separately from an associative array in PHP?

Use array_keys() to get all the keys and array_values() to get all the values of an associative array. Both return a new array.

<?php
$data = ["key1" => "value1", "key2" => "value2", "key3" => "value3"];

print_r(array_keys($data));
print_r(array_values($data));
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => key1
[1] => key2
[2] => key3
)
Array
(
[0] => value1
[1] => value2
[2] => value3
)

If you need both together, use a foreach loop with the key and value.

<?php
$data = ["key1" => "value1", "key2" => "value2", "key3" => "value3"];

foreach ($data as $key => $value) {
    echo $key . " = " . $value . "<br>";
}
?>

Output:

Tutorials Class - Output Window

key1 = value1
key2 = value2
key3 = value3


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.