← Back to Chapters

PHP Array Key Functions

? PHP Array Key Functions

? Quick Overview

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().

⚡ Key Concepts

  • array_keys() returns all keys from an array
  • array_key_exists() checks if a key exists
  • array_flip() swaps keys and values

? Syntax & Theory

PHP array key functions help manage associative arrays where meaningful keys are used instead of numeric indexes.

? Example 1: array_keys()

? View Code Example
// Extracting all keys from an associative array
<?php
$fruits = array("a" => "Apple", "b" => "Banana", "c" => "Cherry");
$keys = array_keys($fruits);
print_r($keys);
?>

? Explanation

The function returns an indexed array containing only the keys from the original array.

? Example 2: array_key_exists()

? View Code Example
// 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";
?>

? Explanation

If the specified key is present, the function returns true.

? Example 3: array_flip()

? View Code Example
// Swapping keys and values of an array
<?php
$fruits = array("a" => "Apple", "b" => "Banana", "c" => "Cherry");
$flipped = array_flip($fruits);
print_r($flipped);
?>

? Explanation

Values become keys and keys become values in the resulting array.

? Use Cases

  • Validating request parameters
  • Extracting keys for reporting
  • Reversing lookup tables

✅ Tips & Best Practices

  • Ensure values are unique when using array_flip()
  • Use array_key_exists() for associative arrays
  • Combine with loops for advanced logic

? Try It Yourself

  • Check for a key in a shopping cart array
  • Extract keys from a movie list
  • Flip country codes and names