Set value of an array using xpath notation

This is a continuation to my previous article on how to get values of multi-dimensional arrays using xpath notation.

This time I will show you how to set a value of an array using the same xpath notation (root/branch/leaf).

Get values of multi-dimensional arrays using xpath notation

Sometimes we have a value burried deep within a multi-dimensional array. In order to access it we usually end up doing something like this:

  1. $value = $array['a']['b']['c'];

hoping that all the keys are set. However, we have a problem if 'b' is not set or any other of the "path" keys are missing.

Wouldn't it be nice if we could get the value using something similar to xpath, e.g. "a/b/c" and specify the default value if the chain is broken? I thought it would and wrote this little function or/and extension to ArrayObject.

Extract all keys from a multidimensional array

Although PHP boasts a huge number of array related functions, unfortunately there is no native function to extract keys from a multidimensional array because array_keys only supports one-dimensional arrays.

For those occasions when you need it, array_keys_multi might help you.

Add array capabilities to DOMDocument class

Unfortunately the native PHP's DOMDocument class does not allow you to create an xml document from a multidimensional array or save it to one.

Here is a class, which adds these capabilities - by using DOMDocumentExt you can now call loadArray or saveArray functions to do the loading and saving tasks respectively.

As an added bonus you can also use function called getPathValue, which accepts one parameter - $path - a string in root/child1/child2/../childN format. It will convert the current document tree to an array and will return the contents of the specified path if such exists (or null if such path does not exist).

Remove values from an array

Prototype.js library has a handy function called Array.without, which "produces a new version of the array that does not contain any of the specified values.".

Quite often one might need to do the same thing in PHP. Here is a function for those occasions.

Showing 1 - 5 of 5 results