If your array keys are not repeated between them, you can do the following:
$todosArrays = $IdUserOnline2 + $IdUserComum2 + $IdUserNovo2;
$IdsInteracoes = implode(',',$todosArrays);
You can also use the array_merge
function if the array keys are repeated
$todosArrays = array_merge($IdUserOnline2, $IdUserComum2, $IdUserNovo2);
$IdsInteracoes = implode(',',$todosArrays);
Remember that in the case of array_merge
, check that the previous variables are arrays , avoiding errors:
$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);
Verifying conditions use a ternary operator .
The logic is simple: It checks if the variable exists, if it does not exist, it initializes it as a blank array . Complete Example .
PHP 7 +
A new operator was implemented in PHP 7 called Null Coalesce Operator , where you need to set a default value if the previous expression returns null.
With it, even if the variable is not set, PHP will not will generate Notice
, working the same way as ||
of Javascript.
So we could simplify the above code to:
$IdUserOnline2 = $IdUserOnline2 ?? [];
$IdUserComum2 = $IdUserComum2 ?? [];
$IdUserNovo2 = $IdUserNovo2 ?? [];
$todosArrays = array_merge($IdUserOnline2, $IdUserComum2, $IdUserNovo2);
$IdsInteracoes = implode(',',$todosArrays);