0

I was wondering if its possible, to loop through an array but have each key as a variable?

My current code is below, with an example expected output:

<?php

   $arr = array(array('id' => 24, 'name' => 'luigi'), array('id' => 12, 'name' => 'luiginsd'));

   foreach ($arr as $value) {

      echo $id . '<br />';

   }

/*

which would output:

24<br />
12<br />

*/

?>

All help is appreciated.

2 Answers 2

5

Use extract:

foreach ($arr as $value) {
   extract($value);
   echo $id.'<br />';
}

extract will iterate through an associative array and initialize a variable (presumably using variable variables) of the same name as the key in the array in the current scope containing the associated value.

Just for fun, here's what I think extract does under the hood:

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

Note that extract does not necessarily import these variables into global scope, they are imported into the current symbol table.

Sign up to request clarification or add additional context in comments.

Comments

3

I suggest you avoid extract(); it makes tracing the origin/heritage of a variable impossible (without either assumptions or code execution). A much cleaner way to do this is:

foreach ($arr as $value) {
  echo $value['id'] . '<br />';
}

1 Comment

fair enough; I think the OP asked for something s/he doesn't actually want, but good point.

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.