Chris
Chris

Reputation: 6233

How to use a value from one foreach loop in the second one?

I would like to know how to the following: I have 2 foreach loops, one inside the other. For example:

foreach($a as $b) { 
    foreach($c as $d) { 
        echo $b; 
    }
}

Now this code snippet doesnt make any sense, but what I would like to know is how to get the value of the first foreach loop (here the $b) into the second foreach loop. Because in this example the $b would not be outputted.

So how can I kind of set the variable $b as global in order to use it in the second foreach loop?

Upvotes: 0

Views: 131

Answers (5)

sankar d.
sankar d.

Reputation: 51

$b is accessed as many time as you inner loop 'loops'.

Upvotes: 0

Bas Slagter
Bas Slagter

Reputation: 9929

Check first whether or not you loops run correctly...start with the outer one, than check the inner one...if that is all ok, you must be able to succesfully print a variable from the outer loop scope.

Upvotes: 0

baklap
baklap

Reputation: 2173

Learn something about scoping http://php.net/manual/en/language.variables.scope.php

As you will read, it's already accessible.

Upvotes: 0

Mob
Mob

Reputation: 11098

It's already accessible.

foreach($a as $b) { 
    foreach($c as $d) { 
        echo $b; //  $b can be accessed
    }
}

Upvotes: 1

JRL
JRL

Reputation: 77995

You don't need to do that, $b will be accessible in the inner loop by default.

Upvotes: 0

Related Questions