How to translate this if javascript to PHP?

Asked

Viewed 80 times

-1

How this if in javascript would look 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 be the in_array?

  • what is in the variable "n"?

  • What is in the variable n and the variable $telefone is as string or array?

  • After the questions I saw that it would be better to complete the code

2 answers

4

In PHP, a solution would be like this:

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

Explanation

This test you have in the code is a little strange and ends up making it difficult to read, not giving clear idea of your intention.

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

See the following example:

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

However, it would be better to use the repeat da String, which is much clearer in its intention:

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

Even if the value to repeat is not a string can always turn it into string and then apply the repeat:

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

In php has the function str_repeat who does precisely the same:

echo str_repeat('a', 11); //aaaaaaaaaa

2


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

Code:

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

Testing at Ideone

  • Um... interesting and more efficient

Browser other questions tagged

You are not signed in. Login or sign up in order to post.