preg_match_all array into foreach loop

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
db579
Forum Commoner
Posts: 37
Joined: Sun Jul 18, 2010 6:23 pm

preg_match_all array into foreach loop

Post 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
Idri
Forum Newbie
Posts: 19
Joined: Sun May 29, 2011 9:21 am

Re: preg_match_all array into foreach loop

Post 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>';
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: preg_match_all array into foreach loop

Post 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 />';
  }
 }  
}
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
db579
Forum Commoner
Posts: 37
Joined: Sun Jul 18, 2010 6:23 pm

Re: preg_match_all array into foreach loop

Post by db579 »

@social_experiment

Thanks that works perfectly, could you explain why?
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: preg_match_all array into foreach loop

Post 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.
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply