1

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 - 
        )
)
3
  • the question is: what is the question ..!!?? Commented Feb 7, 2011 at 14:56
  • basically create 3 vars ($mike, $john, $bob) and assign the corresponding elements to each var. I don't want to do $john = $array['john'][0].$array['john'][1].$array['john'][2]... in order to have all elements appended to $john in this case Commented Feb 7, 2011 at 14:59
  • 1
    @Sigtran - the question is "will you write my code for me" Commented Feb 7, 2011 at 15:26

2 Answers 2

5

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 - 
)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.