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

报告相同问题?

悬赏问题

  • ¥50 用AT89C52单片机设计一个温度测量与控制电路
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库