0

i have an array

Array ( [0] => Array ( [username] => phizy [id] => 1 ) [1] => Array ( [username] => rapik [id] => 4 ) [2] => Array ( [username] => asas [id] => 5 ) )

how do i extract and put them in php variables?

<li><?php $username." with id of ".$userid."</li>";

thank you

3 Answers 3

2

If you really want to turn all the keys of an array into variables, you can use the extract() function.

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

Comments

1

Try like this:

foreach($array as $arobj)
{
    ?>
    <li><?php $arobj['username']." with id of ".$arobj['id']; ?></li>
    <?php
}

or, if you want to assign to the variable then,

foreach($array as $arobj)
{
    $username =  $arobj['username'];
    $userid = $arobj['id'];
    ?>
    <li><?php $username." with id of ".$userid; ?></li>
    <?php
}

2 Comments

<li><?php echo $username." with id of ".$userid; ?></li> (good answer just missed out the echo)
You can leave out the echo if you write it as <?= instead of <?php.
0

Just for fun, if you have to assign variables base on array key, you can try this:

foreach($array as $subArr)
{
  foreach($subArr as $key=>$value)
  {
    $$key=$value;
  }
  echo "<li>$username with id of $id.</li>";
}

Document

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.