note 126981 rejected from function.usort by cmb

From: Date: Mon, 11 Apr 2022 10:27:58 +0000
Subject: note 126981 rejected from function.usort by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-218145@lists.php.net to get a copy of this message
Note Submitter: mail at bemcalavera dot com ---- I'm reporting a strange behavior of usort while trying to sort array (with number index in string format) by subarray item value (see example): $example = array( "1" => array("tit" => "title 1", "val" => 2), "2" => array("tit" => "title 2", "val" => 10), "3" => array("tit" => "title 3", "val" => 5) ); usort( $example, function ($a, $b) { if ( $a["val"] == $b["val"] ) { return 0; } if ( $a["val"] < $b["val"] ) { return 1; }else{ return -1; } } In this case usort will mess up all the values of "val" items (!), and in some cases it creates a new item (with just the "val" field in the new subarray).

« previous php.notes (#218145) next »