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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度