looping

0 ujwal dhakal · October 20, 2014
when do we use foreach twice?

Post a Reply

Replies

Oldest  Newest  Rating
0 Jeremy Benson · October 20, 2014
two different methods might be handy for different reasons.

$sqlReturned = array(array('userName' => 'Jeremy', 'age' => 33), array('userName' => 'Bob', 'age' => 23), array('userName' => 'Jim', 'age' => 18));

foreach($sqlReturned as $L1)

{

  foreach($L1 as $L2 => $val)

 {

   if($L2 === 'userName')

  {

   echo $val . '<br/>';

 }

 }

}

There's also...


foreach($sqlReturned as $key => $list)
{

  echo $sqlReturned[$key]['userName'] . '<br/>';

}


The first method lets you do a check for if the key exists... I guess that would be handy in some cases where user input is creating the query string, and you don't know exactly what data is coming back but you want to check and see if it's there?
0 Jeremy Benson · October 20, 2014
The first method adds a lot of complexity because you could do something like this...



$sqlReturned = array(array('userName' => 'Jeremy', 'age' => 33), array('userName' => 'Bob', 'age' => 23), array('userName' => 'Jim', 'age' => 18));

foreach($sqlReturned as $L1)

{

  foreach($L1 as $L2 => $val)

 {

   if($L2 === 'video games')

  {

    // the user obviously searched our site for video games lets offer a
  // special coupon for our new release and see if we can win him over as
   // a satisfied repeat customer.

 }

 }

}

sorry, I just clued into this while typing it. I'm kind of learning and answering at the same time.
  • 1

PHP

107,341 followers
About

Server-side, HTML embedded scripting language used to create dynamic Web pages.

Links
Moderators