Home > Blockchain >  php 2 foreachloops
php 2 foreachloops

Time:12-09

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?

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

CodePudding user response:

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.

  • Related