Page 1 of 1
preg_match_all array into foreach loop
Posted: Sat Jun 25, 2011 6:16 am
by db579
Hi, I'm trying to use preg_match_all to match a set of values and store them as an array that I can loop through using foreach. I've tried to do it like this:
Code: Select all
$pattern = '/<span class="Normal-C0?">.+?<\/span>/';
preg_match_all($pattern,$table,$match);
foreach($match as $entry){echo $entry}
Using print_r $match outputs the right values in what looks to me like an array so the pattern matching is fine. Also I know the foreach loop is OK because if substituting an arbitrary array for $match outputs correctly. The code as above however just outputs the word 'Array'. Can anyone help? Thanks
Re: preg_match_all array into foreach loop
Posted: Sat Jun 25, 2011 7:39 am
by Idri
This is probably because the contents aren't what you think they are. I'm suspecting it's a 2d (if not more) array.
Does your print_r output look like this?
Code: Select all
Array
(
[0] => Array
(
[0] => A
[1] => B
[2] => C
)
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
(If your output is just on place your print_r between <pre> tags)
Code: Select all
echo '<pre>'; print_r(/*your values*/); echo '</pre>';
Re: preg_match_all array into foreach loop
Posted: Sat Jun 25, 2011 9:53 am
by social_experiment
Have you tried :
Code: Select all
foreach ($match as $key => $value)
{
if (is_array($value))
{
foreach ($value as $ikey => $ivalue)
{
echo $ikey . ' => ' . $ivalue . '<br />';
}
}
}
Re: preg_match_all array into foreach loop
Posted: Sat Jun 25, 2011 8:18 pm
by db579
@social_experiment
Thanks that works perfectly, could you explain why?
Re: preg_match_all array into foreach loop
Posted: Sun Jun 26, 2011 8:16 am
by social_experiment
The if(is_array) line checks to see if the value contained in $value is an array and if it is it treats it as such with the foreach loop, which prints out the contents of the array.