PHP
Extract All Keys or Values from a PHP Array
Discover how to quickly retrieve all keys using `array_keys()` or all values using `array_values()` from a PHP array as a new numerically indexed array for various tasks.
<?php
$userDetails = [
'id' => 101,
'name' => 'Alice',
'email' => '[email protected]',
'status' => 'active'
];
echo "Original array:
";
print_r($userDetails);
// Get all keys
$allKeys = array_keys($userDetails);
echo "
All keys:
";
print_r($allKeys);
// Get all values
$allValues = array_values($userDetails);
echo "
All values:
";
print_r($allValues);
// Example with specific search value for array_keys()
$productStatus = [
'productA' => 'in_stock',
'productB' => 'out_of_stock',
'productC' => 'in_stock',
'productD' => 'discontinued'
];
$inStockProducts = array_keys($productStatus, 'in_stock');
echo "
Products that are 'in_stock':
";
print_r($inStockProducts);
// Get keys with strict type checking
$mixedValues = ['a' => 1, 'b' => '1', 'c' => 2];
$strictKeys = array_keys($mixedValues, 1, true);
echo "
Keys with value 1 (strict type check):
";
print_r($strictKeys);
?>
How it works: The `array_keys()` function returns all the keys or a subset of the keys of an array. You can optionally pass a search value to retrieve only keys that have that specific value. The `array_values()` function returns all the values from an array, re-indexing them numerically. Both functions are excellent for extracting specific parts of an array to use in other operations or for iteration.