How to simplify the following IF in PHP?

Asked

Viewed 713 times

16

I had to do a check to concatenate content to a variable, but I think the service got a bit "pig" and wanted to see if someone could help me simplify this check

if($IdUserOnline2){
    $IdsInteracoes .= implode(',',$IdUserOnline2);
    if($IdUserComum2){
        $IdsInteracoes .= ','.implode(',',$IdUserComum2);
        if($IdUserNovo2){
            $IdsInteracoes .= ','.implode(',',$IdUserNovo2);
        }
    }elseif($IdUserNovo2){
        $IdsInteracoes .= ','.implode(',',$IdUserNovo2);
    }
}elseif($IdUserComum2){
    $IdsInteracoes .= implode(',',$IdUserComum2);
    if($IdUserNovo2){
        $IdsInteracoes .= ','.implode(',',$IdUserNovo2);
    }
}elseif($IdUserNovo2){
    $IdsInteracoes .= implode(',',$IdUserNovo2);
}
  • 3

    Our dear, could you explain what you wanted to do when you did this? develop a new logic for sure will be better than trying to fix this(believe) would be great :D you can edit your question with original intent?

  • The intention is already explicit in the question itself, I have to add several arrays to 1 only, however, at a given moment I need to add a prefix containing a "," to separate the arrays and not bugle, after joining the 3 I will have a string with all of them and pass it to a bind_param of mysqli.

  • Humm, why not add all values in a single Array and then create a repeat loop to add a , in each value? as , are because of sql right?

  • i could do this with merge array, but if one of them comes back empty of the error in the function, generating a string of errors, the check has to be individual and the action too...

2 answers

17

In case your keys array do not repeat themselves between them you can do the following:

$todosArrays = $IdUserOnline2 + $IdUserComum2 + $IdUserNovo2;
$IdsInteracoes = implode(',',$todosArrays);

You can also use the function array_merge if the keys to the array repeat

$todosArrays = array_merge($IdUserOnline2, $IdUserComum2, $IdUserNovo2);
$IdsInteracoes = implode(',',$todosArrays);

Recalling that in the case of array_merge, check if the previous variables are arrays, avoiding mistakes:

$IdUserOnline2 = isset($IdUserOnline2) ? $IdUserOnline2 : array();
$IdUserComum2 = isset($IdUserComum2) ? $IdUserOnline2 : array();
$IdUserNovo2 = isset($IdUserNovo2) ? $IdUserOnline2 : array();

// É possível usar um ternário reduzido, porém é preciso inicializar as variáveis antes
// $IdUserOnline2 = $IdUserOnline2 ?: array();
// $IdUserComum2 = $IdUserComum2 ?: array();
// $IdUserNovo2 = $IdUserNovo2 ?: array();

$todosArrays = array_merge($IdUserOnline2, $IdUserComum2, $IdUserNovo2);
$IdsInteracoes = implode(',',$todosArrays);

The verification of conditions uses a ternary operator.

The logic is simple: Checks if the variable exists, if it does not exist, initializes it as a array blank. Full example.


PHP 7+

A new operator has been implemented in PHP 7 called Null Coalesce Operator, indicated for situations where it is necessary to set a default value if the previous expression returns null.

With it, even if the variable is not defined, PHP nay will generate a Notice, functioning in the same way as || javascript.

So we could simplify the above code for:

$IdUserOnline2 = $IdUserOnline2 ?? [];
$IdUserComum2 = $IdUserComum2 ?? [];
$IdUserNovo2 = $IdUserNovo2 ?? [];

$todosArrays = array_merge($IdUserOnline2, $IdUserComum2, $IdUserNovo2);
$IdsInteracoes = implode(',',$todosArrays);
  • 2

    $IdsInteracoes=implode(',',array_merge($IdUserOnline2,$IdUserComum2,$IdUserNovo2)); Much simpler that way

  • I hadn’t noticed yet, but if one of the variables comes empty of the error in these functions, then I would generate a new hierarchy of checks that in the case does not simplify the if

  • the problem is that I did it and even then it returned me error in the array_merge, because one way or another it would go to empty array_merge, checking or not

  • In this case no, because the ternary defines the variable as an empty array case it is not defined.

  • Explain better, where do these three variables come from? They can take on a different value than a array? string for example?

  • as 3 comes from the database, so I have 3 different arrays, which are users of different categories, need together all users listed in the 3 categories in a list to use in a bind_param of mysqli since it does not accept arrays, then I need to join the 3 in a string to use inside a SQL IN function

  • @Rodrigoborth the error of its function (2nd comment) comes from isset(), as I explained above. If the variables at all times are defined, the code does not generate notice.

  • 2

    I like this modification in PHP 7. It makes life a lot easier

  • You can force variables to be arrays so you don’t need to check if they are empty $IdsInteracoes = implode(',', array_merge((array) $IdUserOnline2, (array) $IdUserComum2, (array) $IdUserNovo‌​2));

  • @Oeslei still generates notice http://3v4l.org/LmNJ8

  • @gmsantos The form I put only serves for when all variables are defined, but possibly have values like null or false. When they are not defined the isset, but analyzing the question, I assume that the variables are already defined, otherwise the initial solution itself already generates error.

  • @Oeslei read the comments on this question.

  • +1 for PHP 7 version, I didn’t know that. : S

Show 8 more comments

11


There is a "hierarchy" between "online," "common," and "new," so this way you wrote it is also how I would write it... But in your particular case, I see that the behavior repeats itself inside is outside of each if. That is, just replace everything by just 3 ifs:

$prefixo = '';
if($IdUserOnline2){
    $IdsInteracoes .= implode(',',$IdUserOnline2);
    $prefixo = ',';
}

if($IdUserComum2){
    $IdsInteracoes .= $prefixo . implode(',',$IdUserComum2);
    $prefixo = ',';
}

if($IdUserNovo2){
    $IdsInteracoes .= $prefixo . implode(',',$IdUserNovo2);
}
  • @gmsantos PHP supports "or" as in Javascript? (ex.: null || [] flipped []) Or does it only apply to booleans? If it’s like the first case, you can simplify your answer using this simple form within the array_merge (using the ternary operator does not compensate in that case - there would be a very big line...). In that case your answer would actually be better than mine (in my opinion, as mine is clearer/readable).

Browser other questions tagged

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