Sometimes you want to get just the keys or just the values from an array to use them separately.
Array key and value extraction in PHP
<?php // Extract keys from an array $keys = array_keys($array); // Extract values from an array $values = array_values($array); ?>
array_keys() returns a new array with all the keys from the original array.
array_values() returns a new array with all the values from the original array, re-indexed starting at 0.
<?php // Example with associative array $person = ['name' => 'Alice', 'age' => 30]; $keys = array_keys($person); $values = array_values($person); print_r($keys); print_r($values); ?>
<?php // Example with empty array $empty = []; $keys = array_keys($empty); $values = array_values($empty); print_r($keys); print_r($values); ?>
<?php // Example with indexed array $numbers = [10, 20, 30]; $keys = array_keys($numbers); $values = array_values($numbers); print_r($keys); print_r($values); ?>
<?php // Example with single element array $single = ['only' => 'one']; $keys = array_keys($single); $values = array_values($single); print_r($keys); print_r($values); ?>
This program creates an array of fruits with their colors, then extracts and prints the keys (fruit names) and values (colors) separately.
<?php // Create an associative array $fruits = [ 'apple' => 'red', 'banana' => 'yellow', 'grape' => 'purple' ]; // Print original array echo "Original array:\n"; print_r($fruits); // Extract keys $fruit_names = array_keys($fruits); // Extract values $fruit_colors = array_values($fruits); // Print keys echo "\nExtracted keys (fruit names):\n"; print_r($fruit_names); // Print values echo "\nExtracted values (fruit colors):\n"; print_r($fruit_colors); ?>
Time complexity: Both array_keys() and array_values() run in O(n) time, where n is the number of elements.
Space complexity: They create new arrays, so space used is O(n).
A common mistake is expecting array_values() to keep original keys; it always re-indexes starting at 0.
Use array_keys() when you need to work with keys only, and array_values() when you want just the values without keys.
You can get all keys from an array using array_keys().
You can get all values from an array using array_values().
These functions help separate keys and values for easier processing.