[SOLVED] Sort an array by a number in a string

Issue

I have the following array:

$anArray = ['aValue (17)', 'anotherValue (5)', 'someData (3)']

How can I sort this array by the number in the brackets?

The result should look like that:

$anArray = ['someData (3)', 'anotherValue (5)', aValue (17)']

Solution

This can solve your problem

$anArray = ['aValue (17)', 'anotherValue (5)', 'someData (3)'];

$anArray = sortMyArray($anArray);
function sortMyArray($arr){
    $keyValueArray = [];
    foreach ($arr as $element) {

        // ( position
        $start  = strpos($element, '(');
    
        // ) position
        $end    = strpos($element, ')', $start + 1);
        
        $length = $end - $start;
    
        // Get the number between parantheses
        $num = substr($element, $start + 1, $length - 1);
    
        // check if its a number
        if(is_numeric($num)){
            $keyValueArray[$num] = $element;
        }
    }
    
    // Sort the array by its keys
    ksort($keyValueArray);
    
    // reassign your array with sorted elements
    $arr = array_values($keyValueArray);
    return $arr;
}

Answered By – mmh4all

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *