Mike
Mike

Reputation: 11

php loop array assignment

I have an array that looks like the one below. I would like to iterate over a loop and assign to 3 different variables the corresponding strings. so for instance:

Output:

$mike = 'foo - ';
$john = 'bar foo foo - bar foo foo - bar foo bar - '
$bob =  'bar foo bar bar foo - bar foo - '

What would be a short(est) way of doing this? thanks

Initial array

Array
(
    [mike] => Array
        (
            [0] => foo -
        )
    [john] => Array
        (
            [0] => bar foo foo - 
            [1] => bar foo foo - 
            [2] => bar foo bar - 
        )
    [bob] => Array
        (
            [0] => bar foo bar - 
            [1] => bar foo - 
            [2] => bar foo - 
        )
)

Upvotes: 1

Views: 1990

Answers (2)

Mark Baker
Mark Baker

Reputation: 212412

use extract() and implode()

$a = array( 'mike'  => array('foo -'),
            'john'  => array('bar foo foo - ',
                             'bar foo foo - ',
                             'bar foo bar - '
                            ),
            'bob'   => array('bar foo bar - ',
                             'bar foo - ',
                             'bar foo - '
                            )
          );

foreach($a as $k => $v) {
    $a[$k] = implode(' ',$v);
}
extract($a);

var_dump($mike);
var_dump($john);
var_dump($bob);

Upvotes: 1

netcoder
netcoder

Reputation: 67695

This is a case for variables variables:

foreach ($array as $key => $values) {
   $$key = implode($values);
}

However, you may not really need them. I would use an array instead:

$result = array();
foreach ($array as $key => $values) {
   $result[$key] = implode($values);
}

So you'd get:

Array
(
    [mike] => foo -
    [john] => bar foo foo - bar foo foo - bar foo bar - 
    [bob] => bar foo bar - bar foo - bar foo - 
)

Upvotes: 5

Related Questions