phparrayssortingassociative-arraycustom-sort

Move elements with a key in a whitelist array to the end of the array


I have the following array and it is changeable from time to time.

Array
(
    [For Sale] => For Sale
    [Sold] => Sold
    [To Let] => To Let
    [Let] => Let
    [Under Offer] => Under Offer
    [Exchanged] => Exchanged
    [Withdrawn] => Withdrawn
    [Acquired] => Acquired
)

No matter what's the initial sequence was but when the page loads it should look like

Array
    (
        [For Sale] => For Sale       
        [Under Offer] => Under Offer
        [Exchanged] => Exchanged
        [Withdrawn] => Withdrawn
        [Acquired] => Acquired
        [Sold] => Sold
        [To Let] => To Let
        [Let] => Let
    )

Basically these three elements should stay at the bottom of the array.

[Sold] => Sold
[To Let] => To Let
[Let] => Let

Solution

  • Here I've used in_array() to match the key with the given keys 'Sold','To Let','Let', then unset that key from $input array and push that key value to the array.

    <?php
    $input = array(
        'For Sale' => 'For Sale',
        'Sold' => 'Sold',
        'To Let' => ' To Let',
        'Let' => 'Let',
        'Under Offe' => 'Under Offer',
        'Exchanged' => 'Exchanged',
        'Withdrawn' => 'Withdrawn',
        'Acquired' => 'Acquired'
    );
    
    foreach ($input as $key => $val) {
        if (in_array($key, array('Sold', 'To Let', 'Let'))) {
            unset($input[$key]);
            $input[$key] = $val;
        }
    }
    
    echo "<pre>";
    print_r($input);
    ?>
    

    This will Output :

    Array
    (
        [For Sale] => For Sale
        [Under Offe] => Under Offer
        [Exchanged] => Exchanged
        [Withdrawn] => Withdrawn
        [Acquired] => Acquired
        [Sold] => Sold
        [To Let] =>  To Let
        [Let] => Let
    )