Current Location: Home> Latest Articles> PHP Array Key-Value Swapping Methods and Best Algorithm Selection

PHP Array Key-Value Swapping Methods and Best Algorithm Selection

M66 2025-07-11

PHP Array Key-Value Swapping Methods and Best Algorithm Selection

In PHP, an array is an ordered, key-controlled data structure. Key-value swapping refers to exchanging the keys and values in an array to create a new one. Different algorithms can be chosen to implement key-value swapping based on the data type of array elements.

Algorithm Selection

Data TypeAlgorithm
Associative Arrays (Keys are strings or integers)array_flip()
Indexed Arrays (Keys are integers)asort() + array_keys()
Object Arraysarray_map() + custom callback function

Practical Examples

Associative Arrays

When the keys of an array are strings or integers, the array_flip() function can be used to swap keys and values.

$arr = ['name' => 'John', 'age' => 30];
$flippedArr = array_flip($arr);
print_r($flippedArr);

Output:

Array
(
    [John] => name
    [30] => age
)

Indexed Arrays

For indexed arrays with integer keys, use asort() to sort the array first, and then use array_keys() to retrieve the new keys.

$arr = [1, 2, 3, 4, 5];
asort($arr);
$flippedArr = array_keys($arr);
print_r($flippedArr);

Output:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Object Arrays

For arrays containing objects, you can use array_map() with a custom callback function to swap keys and values.

class Person {
    public $name;
    public $age;
}

$person1 = new Person();
$person1->name = 'John';
$person1->age = 30;

$person2 = new Person();
$person2->name = 'Mary';
$person2->age = 25;

$arr = [$person1, $person2];
$flippedArr = array_map(function ($obj) {
    return [$obj->name, $obj];
}, $arr);
print_r($flippedArr);

Output:

Array
(
    [John] => Person Object
    (
        [name] => John
        [age] => 30
    )
    [Mary] => Person Object
    (
        [name] => Mary
        [age] => 25
    )
)

Above are several common methods for PHP array key-value swapping with practical examples. By selecting the appropriate algorithm based on the data type, you can improve the efficiency and readability of your code.