Array_values ​​not working with ArrayAccess object

array_values() does not work with an ArrayAccess object. and array_keys()

why?

if I can access $object['key'] , I should be able to perform all kinds of array operations

+4
source share
3 answers

No, you misunderstood the ArrayAccess utility. It is not just a kind of wrapper for an array. Yes, a standard example of its implementation uses the private variable $array , the functionality of which ends with the class, but this is not particularly useful. Often you can just use an array.

One good example of ArrayAccess is when the script does not know which variables are available.

As a rather stupid example, imagine an object that worked with a remote server. Resources on this server can be read, updated, and deleted using the API over the network. The programmer decides that they want to wrap this functionality with an array-like syntax, so $foo['bar'] = 'foobar' sets the bar resource on this server so that foobar and echo $foo['bar'] retrieve it. The script has no way of knowing which keys or values ​​are present without trying to use all possible values.

So, ArrayAccess allows you to use array syntax to install, update, retrieve, or remove from an object with an array type syntax: nothing more, no less.

Another Countable interface allows the use of count() . You can use both interfaces in one class. Ideally, there would be more such interfaces, possibly including those that can execute array_values or array_keys , but they currently do not exist.

+4
source

ArrayAccess very limited. It does not allow to use the built-in functions array_ (no existing interface does not work).

If you need to do more array operations on your object, you create a collection. Use it to manipulate the collection.

So create an object and add an ArrayObject . This implements IteratorAggregate , Traversable , ArrayAccess , Serializable and Countable .

If you need keys, just add the array_keys method:

 public function array_keys($search_value = null, $strict = false) { return call_user_func_array('array_keys', array($this->getArrayCopy(), $search_value, $strict)); } 

Then you can:

 foreach ($object->array_keys() as $key) { echo $object[$key]; } 
+2
source

ArrayObject / ArrayAccess allows objects to work like arrays, but they are still objects. So instead of array_keys() (which only works with arrays), you should use get_object_vars() , for example:

 var_dump(array_keys(get_object_vars($ArrObj))); 

or transform your ArrayObject by injecting it into an array using (array) $ArrObj , for example:

 var_dump(array_keys((array)$ArrObj)); 
0
source

Source: https://habr.com/ru/post/1401267/


All Articles