Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

php 2 foreachloops

I want to output the key of the associative array, if the preg_match function returns true.

But somehow the second foreach loop returns just one key.

Why is this so?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is my php code:

<?php

     $log = file('ab.boerse.de.access.log.2');

     foreach ($log as $key => $value)
     {
         $result = explode(" ", $value);

         echo "<pre>";
         print_r($result);
         echo "</pre>";

         foreach ($result as $key2 => $value2)
         {
             echo "<pre>";
             print_r($key2);
             echo "</pre>";

             if (preg_match("/somedata/", $value2))
             {
                 print_r($key2);
             }
             else
             {
                 break;
             }
         }
     }
            
 ?>

And this is the outputed array with the key "0" below it:

Array (
    [0] => localhost
    [1] => somedata
    [2] => somedata
    [3] => somedata
    [4] => somedata
    [5] => somedata
    [6] => somedata
    [7] => somedata
    [8] => somedata
    [9] => somedata
    [10] => somedata
    [11] => somedata
    
) 0

>Solution :

First items value is localhost and not somedata, so the regex does not match anything and it executes the break ending the 2nd foreach. Try using continue instead of break if you want to skip unwanted items. continue terminates just the current iteration of the cycle and continues with next item.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading