duanhong4274 2018-08-14 09:38
浏览 30
已采纳

如果指定的参数之一不是数组,则阻止array_merge合并数组

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.

  • 写回答

3条回答 默认 最新

  • dqwh0108 2018-08-14 09:42
    关注

    Use is_array function to check if a variable is an array or not.

    $mergedArray = array_merge($mergedArray, $a, $b, is_array($c) ? $c : array());
    

    If $c is an array, combine it. If not, just combine with empty array which doesn't affect the result.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历