How to translate this if javascript to PHP?

0

How would this if in javascript be in php?

        ...
        telefone = "11222223333"; // exemplo
        for (var n = 0; n < 10; n++) {
            if (telefone == new Array(11).join(n) || telefone == new Array(12).join(n)){
                return false;
            }
        }

Would it be in_array?

    
asked by anonymous 18.05.2018 / 18:48

2 answers

1

It is noticed that the intention is to verify if the variable telefone has a sequence with only the same number. In this case, in PHP, you can use the array_unique with count . If the result is 1 , it means that the string has the repetitive sequence.

Code:

if( count(array_unique(str_split($telefone))) == 1 ){
    return false;
}

Try Ideone

    
18.05.2018 / 19:42
2

In PHP, a solution would look like this:

if ($telefone == str_repeat($n, 11) || $telefone == str_repeat($n, 12)){
     return false;
}

Explanation

This test in the code is a bit strange and ends up making it difficult to read, not giving clear idea of what it means.

What new Array(11).join(n) does is create an array of a certain size in which all the houses have undefined , and put everything together with the last tab. But the undefineds that are in all the houses are represented as empty text, soon it will be with string in which the separator was repeated several times.

See the following example:

console.log(new Array(11).join('a'));

However, it would be best to use repeat String >, which is much clearer in its intention:

console.log('a'.repeat(11));

Even if the value to be repeated is not a string you can always transform it to string and then apply repeat :

let x = 3;
console.log(x.toString().repeat(11));

In php you have the str_repeat function that does precisely the same thing:

echo str_repeat('a', 11); //aaaaaaaaaa
    
18.05.2018 / 19:00