Swapping Array Keys and Values in PHP: array_flip vs Manual Method
This article explains two efficient ways to swap keys and values of a PHP array—using the built‑in array_flip() function and a manual loop—compares their performance with a microtime benchmark, and provides complete code examples for each approach.
In PHP, swapping an array's keys and values can be done efficiently using two different methods, which are compared in this tutorial.
Method 1: array_flip() Function
$arr = ['foo' => 'bar', 'baz' => 'qux'];
$reversedArr = array_flip($arr);Method 2: Manual Swapping
$arr = ['foo' => 'bar', 'baz' => 'qux'];
$newArray = [];
foreach ($arr as $key => $value) {
$newArray[$value] = $key;
}Practical Example
We use PHP's microtime(true) function to measure the execution time of both methods on a large array of 100,000 elements.
$arr = range(1, 100000); // create an array with 100,000 elements
// array_flip() method
$startTime = microtime(true);
$reversedArr = array_flip($arr);
$endTime = microtime(true);
$timeTakenArrayFlip = $endTime - $startTime;
// manual swapping method
$startTime = microtime(true);
$newArray = [];
foreach ($arr as $key => $value) {
$newArray[$value] = $key;
}
$endTime = microtime(true);
$timeTakenManual = $endTime - $startTime;The benchmark results show which approach is faster for large datasets.
Java learning resources
C language learning resources
Frontend learning resources
C++ learning resources
PHP learning resources
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.