Using PHP array_flip() Function: Syntax, Examples, and Practical Applications
This article explains the PHP array_flip() function, detailing its syntax, parameters, return values, and providing multiple code examples that demonstrate how to swap keys and values, remove duplicates, locate values, and generate enumerated arrays for practical backend development tasks.
PHP's array_flip() function swaps the keys and values of an array, turning original keys into values and vice versa. Its syntax is array array_flip ( array $array ) , and it returns a new array with the exchanged pairs.
Example usage shows an associative array $old_array = array("apple"=>"fruit", "carrot"=>"vegetable"); being flipped with $new_array = array_flip($old_array); and displayed using var_dump($new_array); , producing a result where "fruit" and "vegetable" become keys.
<code>$old_array = array("apple"=>"fruit", "carrot"=>"vegetable");
$new_array = array_flip($old_array);
var_dump($new_array);
</code>One practical application is removing duplicate values: an indexed array is flipped, unique keys are kept with array_unique() , and then flipped back, yielding an array without duplicates.
<code>$old_array = array("apple", "banana", "carrot", "apple", "grape", "banana");
$new_array = array_flip($old_array);
$new_array = array_unique($new_array);
$new_array = array_flip($new_array);
print_r($new_array);
</code>Another use case is quickly locating a value's original key by flipping the array and checking existence with isset() or array_key_exists() .
<code>$old_array = array("apple"=>"fruit", "banana"=>"fruit", "carrot"=>"vegetable");
$new_array = array_flip($old_array);
if (isset($new_array["fruit"])) {
echo "fruit is found in array";
}
</code>For generating enumerated arrays, array_flip() can turn a list of values into keys, which are then paired with sequential numbers using range() and array_map() , finally merging with array_replace() to produce an array mapping each item to an index.
<code>$old_array = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
$new_array = array_flip($old_array);
$enum_array = array_map(function(){static $index = 1; return $index++;}, range(1, count($old_array)));
$new_array = array_replace($new_array, $enum_array);
print_r($new_array);
</code>The article concludes with several recommended learning resources for PHP and related technologies, linking to tutorials on Vue3, Laravel, Swoole, and Workerman.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.