php usort array of objects code example

Example 1: php sort array by object value

/**
 * A generic PHP sorting algorithm that uses `usort` and `strcmp`.
 * `usort` — Sort an array by values using a user-defined comparison function.
 * `strcmp` — Returns < 0 if param 1 is less than param 2; > 0 if param 1 is greater than param 2, and 0 if they are equal.
 */
$questions = [
  { id: 1, ordinal: 55 },
  { id: 2, ordinal: 67 },
  { id: 3, ordinal: 32 },
];

function sortByOrdinal($param1, $param2) {
    return strcmp($param1->ordinal, $param2->ordinal);
}

/* `usort` alters an existing array. */
usort($questions, "sortByOrdinal");

/**
 * $questions = [
 *   { id: 3, ordinal: 32 },
 *   { id: 1, ordinal: 55 },
 *   { id: 2, ordinal: 67 },
 * ];
 */

Example 2: php create array of objects

<?php
class Person
{
    public $name;
    public $age;
    
    function  birthday($age){
    	$age = $age + 1;
        return $age;
    }
}

$person1 = new Person();
$person1->name = 'David';
$person1->age = '23';

$person2 = new Person();
$person2->name = 'Nuno';
$person2->age = '21';
$person2->age = $person2->birthday($person2->age);

$persons = array($person1, $person2);

foreach ($persons as $person) {
    echo 'My name is ' . $person->name . ' and i have ' . $person->age . " years old";
    echo '<br>';
}
?>

Tags:

Php Example