In PHP, working with arrays often requires handling their keys. PHP provides several array functions to retrieve, manipulate, and work with the keys of an array such as array_keys(), array_key_exists(), and array_flip().
array_keys() returns all keys from an arrayarray_key_exists() checks if a key existsarray_flip() swaps keys and valuesPHP array key functions help manage associative arrays where meaningful keys are used instead of numeric indexes.
// Extracting all keys from an associative array
<?php
$fruits = array("a" => "Apple", "b" => "Banana", "c" => "Cherry");
$keys = array_keys($fruits);
print_r($keys);
?>
The function returns an indexed array containing only the keys from the original array.
// Checking if a specific key exists in the array
<?php
$fruits = array("a" => "Apple", "b" => "Banana", "c" => "Cherry");
$exists = array_key_exists("b", $fruits);
echo $exists ? "Key exists" : "Key does not exist";
?>
If the specified key is present, the function returns true.
// Swapping keys and values of an array
<?php
$fruits = array("a" => "Apple", "b" => "Banana", "c" => "Cherry");
$flipped = array_flip($fruits);
print_r($flipped);
?>
Values become keys and keys become values in the resulting array.
array_flip()array_key_exists() for associative arrays