Ask Your Question
1

What is the method to arrange an array in PHP and guarantee that a specific key remains at the top of the sorted list?

asked 2021-06-16 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-04-15 19:00:00 +0000

devzero gravatar image

One method to arrange an array in PHP and guarantee that a specific key remains at the top of the sorted list is by using the usort function and specifying a custom comparison function.

Here's an example code:

$array = array(
    'name' => 'John',
    'age' => 30,
    'gender' => 'male',
);

// Define a custom comparison function
function customSort($a, $b) {
    // specify the key you want to keep at the top
    $specificKey = 'name';

    if ($a == $specificKey) {
        return -1;
    } else if ($b == $specificKey) {
        return 1;
    } else {
        return strcmp($a, $b);
    }
}

// Sort the array using the custom comparison function
uksort($array, 'customSort');

// Print the sorted array
print_r($array);

In this example, the customSort function compares two keys and returns -1 if the first key is the specificKey (name in this case), 1 if the second key is the specificKey, or uses the strcmp function to compare the two keys alphabetically if neither of them is the specificKey. The uksort function then sorts the array using this custom comparison function, resulting in the specificKey ('name') being at the top of the sorted list.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-06-16 11:00:00 +0000

Seen: 9 times

Last updated: Apr 15 '21