I have an array $AR
I have a string "set[0][p1]"
When given this string, I need the best way to access the array at $AR['set'][0]['p1']
I have total control on that string, so I need not to worry from injections and stuff, and I can be sure it will be well formatted. There is no way I can put the p1 inside ' to be "set[0]['p1']"
Check parse_str()
:
parse_str('set[0][p1]', $AR);
Oh, you want to access the index of the array... Here is my take:
getValue($AR, array('set', 0, 'p1'));
Or if you really must use the original string representation:
parse_str('set[0][p1]', $keys);
getValue($AR, $keys);
Disclaimer: I haven't tested this, you might need to use array_keys()
somewhere.
And the helper function:
function getValue($array, $key, $default = false)
{
if (is_array($array) === true)
{
settype($key, 'array');
foreach ($key as $value)
{
if (array_key_exists($value, $array) === false)
{
return $default;
}
$array = $array[$value];
}
return $array;
}
return $default;
}
I would avoid regexing your way into this problem.
My try, which should be able to deal with an arbitrary amount of []
s in the string:
To split the string you can use preg_split
.
$parts = preg_split('%\[?(\w+)\]?%', $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
(More) complete code:
function get_value($string, $array) {
$parts = preg_split('%\[?(\w+)\]?%', $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
foreach($parts as $part) {
$array = $array[$part];
}
return $array;
}
$array = array('set'=>array(array('p1'=>'foo')));
$string = "set[0][p1]";
echo get_value($string, $array); // echoes 'foo'
I leave the error handling to you ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With