How can a foreach loop be modified to sort an array based on a specific property like ["name"] in PHP?

To sort an array based on a specific property like ["name"], you can use a custom sorting function within a foreach loop to compare the values of the property you want to sort by. You can then use a sorting function like usort() to sort the array based on this custom comparison function.

// Sample array with objects
$items = [
    ['name' => 'John', 'age' => 25],
    ['name' => 'Alice', 'age' => 30],
    ['name' => 'Bob', 'age' => 20]
];

// Custom sorting function based on 'name' property
usort($items, function($a, $b) {
    return strcmp($a['name'], $b['name']);
});

// Output sorted array
foreach ($items as $item) {
    echo $item['name'] . ' - ' . $item['age'] . PHP_EOL;
}