Print only one line if there are continuous similar lines

I have a variable $ b = substr ($ r ['pon_port'], 4,2); in the foreach loop. Var dam $ b gives a list of such lines:

string(1) "0" string(1) "0" string(1) "0" string(1) "0" string(1) "0"
string(1) "1" string(1) "1" string(1) "1" string(1) "1" string(1) "1"
string(1) "2" string(1) "2" string(1) "2" string(1) "2" string(1) "2"
string(1) "3" string(1) "3" string(1) "3" string(1) "3" string(1) "3"
string(1) "4" string(1) "4" string(1) "4" string(1) "4" string(1) "4"
string(1) "0" string(1) "0" string(1) "0" string(1) "0" string(1) "0"
string(1) "1" string(1) "1" string(1) "1" string(1) "1" string(1) "1"

What I want is if there is the same continuous line, I want to have only one line> for example, for example: in the dump above. I just want to:

string(1) "0" 
string(1) "1" 
string(1) "2" 
string(1) "3" 
string(1) "4" 
string(1) "0" 
string(1) "1" 
+4
source share
2 answers

If I understand you correctly, you can do this, given the last number:

$lastB = null;
foreach ($foo as $r) //I'm guessing that $r is the dummy variable, based on your code
{
        $b = substr($r['pon_port'],4,2); //You wrote this

        //This part prevents repetitions from happening
        if ($lastB === null || $b != $lastB) var_dump($lastB = $b);
}

(In this case, I dyed the assignment into an argument using var_dump($lastB = $b)two separate statements instead. I find it more neat, but you can separate them if you want.)

- , , :

$lastB = null;
foreach ($foo as $r) //I'm guessing that $r is the dummy variable, based on your code
{
        $b = substr($r['pon_port'],4,2); //You wrote this

        //This part prevents repetitions from happening
        if ($lastB === null || $b != $lastB)
        {
            //do something with $b...
            $lastB = $b;
        }
}

"2 2 7 8 8 7", :

string(1) "2" string(1) "7" string(1) "8" string(1) "7"
0

(, ) , , - . 1-, :

$nums = array(0,0,1,2,2,3,4,0,1,2,2,1,2,1,2,3,3,4,4,4);
print_r($nums);
$nums = implode('',$nums);
$nums = preg_replace('~(\d)((?=\1).)+~','$1',$nums);
$nums = str_split($nums);
print_r($nums)

:

Array
(
    [0] => 0
    [1] => 0
    [2] => 1
    [3] => 2
    [4] => 2
    [5] => 3
    [6] => 4
    [7] => 0
    [8] => 1
    [9] => 2
    [10] => 2
    [11] => 1
    [12] => 2
    [13] => 1
    [14] => 2
    [15] => 3
    [16] => 3
    [17] => 4
    [18] => 4
    [19] => 4
)

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 0
    [6] => 1
    [7] => 2
    [8] => 1
    [9] => 2
    [10] => 1
    [11] => 2
    [12] => 3
    [13] => 4
)
0

Source: https://habr.com/ru/post/1648212/


All Articles