stef
stef

Reputation: 27789

PHP arrays & variable variables

With an array $s_filters that looks like this (many different keys possible):

Array
(
    [genders] => m
    [ages] => 11-12,13-15
)

How can I programatically convert this array to this:

$gender = array('m');
$ages = array('11-12','13-15');

So basically loop through $s_filters and create new arrays the names of which is the key and the values should explode on ",";

I tried using variable variables:

foreach( $s_filters as $key => $value )
{
    $$key = array();
    $$key[] = $value;
    print_r($$key);
}

But this gives me cannot use [] for reading errors. Am I on the right track?

Upvotes: 1

Views: 159

Answers (3)

Mārtiņš Briedis
Mārtiņš Briedis

Reputation: 17772

$gender = $arr['gender'];

What you want there is unreadable, hard to debug, and overall a bad practice. It definitely can be handled better.

Upvotes: 0

You Qi
You Qi

Reputation: 9231

$s_filters = Array
(
    "genders" => "m",
    "ages" => "11-12,13-15"
);

foreach($s_filters as $key=>$value)
{
    ${$key} = explode(',', $value);
}

header("Content-Type: text/plain");
print_r($genders);
print_r($ages);

Upvotes: 0

user142162
user142162

Reputation:

The following code takes a different approach on what you're trying to achieve. It first uses the extract function to convert the array to local variables, then loops though those new variables and explodes them:

extract($s_filters);

foreach(array_keys($s_filters) as $key)
{
    ${$key} = explode(",", ${$key});
}

Upvotes: 2

Related Questions