← Back to Chapters

PHP Array_Flip & Array_Change_Key_Case

? PHP Array_Flip & Array_Change_Key_Case

? Quick Overview

The array_flip() and array_change_key_case() functions in PHP are powerful tools for manipulating array keys. One swaps keys with values, while the other standardizes key casing.

? Key Concepts

  • array_flip() converts values into keys
  • array_change_key_case() normalizes key casing

? Syntax / Theory

  • array_flip(array)
  • array_change_key_case(array, CASE_LOWER | CASE_UPPER)

? Example 1: array_flip()

? View Code Example
// Flip keys and values of an associative array
<?php
$array = array("a" => "apple", "b" => "banana", "c" => "cherry");
$result = array_flip($array);
print_r($result);
?>

? Explanation

The values become keys and the keys become values. Useful for reverse lookups.

? Example 2: array_change_key_case() – Lowercase

? View Code Example
// Convert all array keys to lowercase
<?php
$array = array("a" => "apple", "B" => "banana", "C" => "cherry");
$result = array_change_key_case($array, CASE_LOWER);
print_r($result);
?>

? Example 3: array_change_key_case() – Uppercase

? View Code Example
// Convert all array keys to uppercase
<?php
$array = array("a" => "apple", "b" => "banana", "c" => "cherry");
$result = array_change_key_case($array, CASE_UPPER);
print_r($result);
?>

? Use Cases

  • Normalizing API response keys
  • Creating reverse mappings
  • Case-insensitive data handling

✅ Tips & Best Practices

  • Avoid duplicate values with array_flip()
  • Use key case normalization before comparisons
  • Combine both functions for clean transformations

? Try It Yourself

  • Flip a country-capital array
  • Convert mixed-case keys to uppercase
  • Chain both functions together