Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using nested foreach loop on same array

Tags:

php

Is it ok to loop array again in nested loop and also change the array?

I've an URL's array with entries(as array key) of either an URL or domain:example.com

In case of this entry : domain:example.com I want to remove all URLS containing example.com as domain:

foreach (array_keys($urls1) as $line) {
        if (preg_match('/domain:(.*)/i', $line, $matches)) {
            $domain = $matches[1];
            foreach (array_keys($urls1) as $line2) {
                if ($url_domains[$line2] == $domain) {
                    unset($urls1[$line2]);
                }
            }
        }
    }
like image 293
AgA Avatar asked Nov 01 '22 02:11

AgA


1 Answers

There is no problem looping over it a second time, however you will get yourself and your code into a big knot if you start removing items. My suggestion would be to save a copy and modify that.

This is not ideal, but I'm not sure what you wish to do.

//Make a copy of your array
$URLCopy  = $urls1;

foreach (array_keys($urls1) as $line) {
    if (preg_match('/domain:(.*)/i', $line, $matches)) {
        $domain = $matches[1];
        foreach (array_keys($urls1) as $line2) {
            if ($url_domains[$line2] == $domain) {
                unset($URLCopy[$line2]);
            }
        }
    }
 }
like image 149
Toby Allen Avatar answered Nov 09 '22 20:11

Toby Allen