Answer the question
In order to leave comments, you need to log in
How to remake a nested loop in PHP?
Greetings
There is a nested loop in Python (looks for matches of elements of one list in another):
a = '''
0
1
2
3
4
5
6
7
8
9'''
b = '''
5
4
3
2
1'''
temp = ''
for x in a.split('\n'):
for y in b.split('\n'):
if x == y:
temp = '+ ' + x
break
else:
temp = '- ' + x
print(temp)
Answer the question
In order to leave comments, you need to log in
$a = '
0
1
2
3
4
5
6
7
8
9';
$b = '
5
4
3
2
1';
foreach(explode("\r\n", $a) AS $a_item) {
if ($a_item != '') {
if (in_array($a_item, explode("\r\n", $b))) {
echo '+'.$a_item."\r\n";
}
else {
echo '-'.$a_item."\r\n";
}
}
}
Why would you use any loops? Use standard PHP tools, for example:
<?php
$a = '
0
1
2
3
4
5
6
7
8
9';
$b = '
5
4
3
2
1';
$arrayA = str_split(preg_replace('/\s+/', '', $a));
$arrayB = str_split(preg_replace('/\s+/', '', $b));
$diff = array_diff($arrayA, $arrayB);
print_r($diff);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question