I want array_merge to merge only when the argument specified is an array else skip that argument.
Below is the code,
<?php
$mergedArray = array();
$a = array('Hello');
$b = array('Hi');
$c = 'World';
$mergedArray = array_merge($mergedArray, $a, $b, $c);
print_r($mergedArray);
?>
For the above code, I get a warning that $c
is not an array.
I know that converting it into an array will fix the issue,
$mergedArray = array_merge($mergedArray, $a, $b, (array)$c);
But, $c can be an array or a string
, and if it a string I don't want to include it as a parameter in my array_merge, if it an array I want it to be included. Is there any direct method in php to do it, or do I need to write it in if-else statement.
EDIT:
It doesn't make a difference if I include an empty array by checking is_array($c)
. But if I have to implode that result using a delimiter then it will cause an issue,
Modified code,
<?php
$mergedArray = array();
$a = array('Hello');
$b = array('Hi');
$c = 'World';
$mergedArray = array_merge($mergedArray, $a, $b, is_array($c) ? $c : []);
$result = implode(' | ', $mergedArray);
print_r($mergedArray);
?>
Now for the above code, in case of an empty array
, I will get | at the end of $result
which I don't want.