W
W
weranda2018-02-06 14:38:53
PHP
weranda, 2018-02-06 14:38:53

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):

In Python
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)

As a result, where there are matches, a plus is added, where there are no matches, a minus is added.

I'm trying to do the same in PHP, but it doesn't work / Please tell me how to transfer this cycle to PHP.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stimulate, 2018-02-06
@weranda

$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";
        }
    }
}

P
Pavel Novikov, 2018-07-03
@paulfcdd

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);

As a result, you will get an array that will contain all the values ​​of the $arrayA array that are not in other arrays. And then you can do whatever you want with it - split it into a line, output foreach to a list, etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question