mgldev
mgldev

Reputation: 101

Performing an asort on a collection of objects

Wondering if anybody can help shed any light on what PHP is doing under the hood when performing an asort on a collection of objects.

Take the following snippet:

class NameValuePair
{
    private $name;
    private $value;

    public function __construct($name, $value)
    {
         $this->name = $name;
         $this->value = $value;
    }

    public function getName() { return $this->name; }
    public function getValue() { return $this->value; }
}

$nameValuePairs = [
    new NameValuePair('f', 'f'),
    new NameValuePair('b', 'b'),
    new NameValuePair('z', 'z'),
    new NameValuePair('s', 's')
];

asort($nameValuePairs);

The asort is correctly sorting the array by the $name property of the NameValuePair instances - the resulting array contains objects in the order of bfsz

I have implemented two unit tests - I did not expect the asort to correctly sort the collection and I would always use a usort to sort an array of objects.

Please see this gist for full context and unit tests: https://gist.github.com/mgldev/91386cc6e3d65fc239de60dc1bc46114

General musings

Any thoughts?

Upvotes: 2

Views: 29

Answers (0)

Related Questions