dtqjbbr5283 2017-04-13 12:31
浏览 38
已采纳

如果没有值,则使用默认值进行内爆

I want to show dash(-) if my array is empty after imploding it. Here below is my try so far.

Result with Data in Array -> https://repl.it/HIUy/0

<?php 

$array = array(1,2);
$result = array();
foreach ($array as $curr_arr) {

    $result[] = $curr_arr;
}
echo 'Array With Data - ' .  implode(',', $result);
//Result : Array With Data : 1,2   
?>

Result without Data in Array -> https://repl.it/HIVE/0

<?php 

$array = array();
$result = array();
foreach ($array as $curr_arr) {

    $result[] = $curr_arr;
}
echo 'Array Without Data - ' .  implode(',', $result);
//Result : Array With Data - :    
?>

As you can see in the second result, I am unable to print anything as my array was blank hence I was unable to print anything.

However, I want to print Dash(-) using implode only by using something like array_filter which I already tried but I am unable to do so. Here I have tried this https://repl.it/HIVP/0

<?php 

$array = array();
$result = array();
foreach ($array as $curr_arr) {

    $result[] = $curr_arr;
}
echo 'Array With Data : ' .  implode(',', array_filter($result));
//Result : Array With Data :    
?>

Can someone guide me how to achieve this ?

Thanks

  • 写回答

2条回答 默认 最新

  • douwen3127 2017-04-13 12:40
    关注

    You can check if your array is empty and then return/ echo a Dash:

    if(!empty($array)){
      // Array contains values, everything ok
      echo 'Array with data - ' . implode('yourGlueHere', $array);
    } else {
      // Array is empty
      echo 'Array without data -';
    }
    

    If you want to have it in one line, you could do something like the following:

    echo 'Array with' . empty($array) == false ? '' : 'out' . 'data - ' . empty($array) == false ? implode('glue', $array) : '';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波