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.

php Courses
php Courses
php Courses
Swapping Array Keys and Values in PHP: array_flip vs Manual Method

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

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendArrayarray_flipphp-tutorial
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.