Native PHP Sort array of objects by property

Usually, it is very often necessary to sort the data in an array. But when in the array we have objects it happened little bit difficult.
Fast solution for sorting array objects by property name.
Bacis solution (PHP 5.3+) :

function sortArrayWithObjects($array, $property)
{
    usort($array, function ($a, $b) use ($property) {
        return (($a->$property == $b->$property) ? 0 : (($a->$property < $b->$property) ? -1 : 1));
        //[short version] return strcmp($a->$property, $b->$property);
    });
    return $array;
}

$obj1 = new stdClass();
$obj2 = clone $obj1;
$obj3 = clone $obj2;
$obj1->name = 'B';
$obj2->name = 'C';
$obj3->name = 'A';
$data = [$obj1, $obj2, $obj3];
$result = sortArrayWithObjects($data, 'name');
echo '<pre>';
var_dump($result);
echo '</pre>';

Result:
Continue reading Native PHP Sort array of objects by property

Simple bubble sort on PHP

“Bubble Sort” is a classic sort. It used ~76% of programmers.
Example ↓

function bubbleSort ($data_array = array() ) {
$result_array = $data_array;
$size = sizeof($result_array);
if ($size)
  for( $i = 0 ; $i < $size; $i++) {      
    for( $j = $size-1; $j > $i; $j-- ) { 
      if ( $result_array[$j-1] > $result_array[$j] ) {
            $buf = $result_array[$j-1]; 
            $result_array[$j-1] = $result_array[$j]; 
            $result_array[$j] = $buf;
		}
	}
  }
return $result_array;
}
 
$test_array = array(1, 9, 5, 2, 4, 5, 7, 0, 3, 8, 6); 
$result = bubbleSort ($test_array);
echo '<pre>'; print_R($result); echo '</pre>';

Results ↓
Continue reading Simple bubble sort on PHP