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]);
}
}
}
}
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]);
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With