Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to transform a string to array

Tags:

regex

php

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']"

like image 607
Itay Moav -Malimovka Avatar asked Feb 28 '23 14:02

Itay Moav -Malimovka


2 Answers

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.

like image 183
Alix Axel Avatar answered Mar 06 '23 22:03

Alix Axel


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 ;)

like image 41
Felix Kling Avatar answered Mar 06 '23 21:03

Felix Kling