In PHP is it possible for the array functions such as array_values() and array_key_exists() to be used on an object ?
4 Answers
array_key_exists() used to work for objects, but as of PHP 5.3.0, it doesn't anymore. You should use property_exists() instead.
3 Comments
is_array then array_key_exists or property_exists.array_key_exists still works with objects, the difference being only on static properties. array_walk and array_walk_recursive work too. See codepad.viper-7.com/I55G4X and wiki.php.net/internals/engine/objects#get_propertiesPHP objects can be cast to an array without a method call and with virtually no performance penalty, which will allow you to use any array function you like on the properties.
$arr = (array) $obj;
Using language constructs is almost always substantially faster in PHP than calling a method. isset is considered a language construct.
I realise this has a faint whiff of premature optimisation, but the result of running the following code in PHP 5.3 may surprise you.
<?php
$count = 50000;
class Pants
{
public $mega='wad';
public $pung=null;
}
$s = microtime(true);
for ($i=0; $i < $count; $i++) {
$p = new Pants;
$e = property_exists($p, 'mega');
$e = property_exists($p, 'pung');
}
var_dump(microtime(true) - $s);
$s = microtime(true);
for ($i=0; $i < $count; $i++) {
$p = new Pants;
$p = get_object_vars($p);
$e = isset($p['mega']);
$e = isset($p['pung']);
}
var_dump(microtime(true) - $s);
$s = microtime(true);
for ($i=0; $i < $count; $i++) {
$p = new Pants;
$p = (array) $p;
$e = isset($p['mega']);
$e = isset($p['pung']);
}
var_dump(microtime(true) - $s);
Output:
float(0.27921605110168)
float(0.22439503669739)
float(0.092200994491577)
This clearly demonstrates that the best way to do these kinds of gymnastics in PHP is to rely on whichever method uses the most first-class language constructs and the fewest method calls and the best one I've found is the (array) cast.
Comments
For the case of array_values(), use get_object_vars() to get its public properties (depends on the scope of the client code, if you want to obtain protected and private properties).
If you want something more OO, ReflectionObject can do quite a lot.
1 Comment
array_values() as array_keys(). Bah. But something worth reading I hope, for you.If you absolutely need the functionality in array_values and array_keys, you can do this: $keys = array_keys(get_object_vars($obj)) and $values = array_values(get_object_vars($obj))
A better and more OO way would be to create an interface with methods for keys and values. Then implement those methods in your class to get the keys and values. Other array-like interfaces are neatly presented in ArrayIterator class.