php 检查数组是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7807630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:24:12  来源:igfitidea点击:

Check if array is not empty

phparrays

提问by Keith Power

********Update**********

********更新**********

var_dump: string(0)""

var_dump: string(0)“”

I am trying to check if part of an array is not empty then display code but the code get's displayed anyway.

我正在尝试检查数组的一部分是否不为空,然后显示代码,但无论如何都会显示代码。

I have tried !is_null !empty. I am not really sure which should be correct or should I go with: if (sizeof($book['Booking']['comments'])>0)

我试过了!is_null !empty。我不确定哪个应该是正确的,或者我应该选择: if (sizeof($book['Booking']['comments'])>0)

Code:

代码:

<?php if (!empty($book['Booking']['comments'])) {?>
    <table width="100%" border="0">
        <tbody>
            <tr>
                <td style="font-family:'Lucida Grande', sans-serif;font-size:12px;font-weight:normal;color:#666666;">
                    <?=$book['Booking']['comments']?>
                </td>
            </tr>
        </tbody>
    </table>
<? } ?>

Array:

大批:

Array
(
[Booking] => Array
    (
        [id] => 109
        [user_id] => 1
        [corporate_account_id] => 0
        [id_ref] => RES000109
        [price] => 178.00
        [arrival] => 2011-10-18 00:00:00
        [departure] => 2011-10-19 00:00:00
        [rate_title] => 
        [adult_guests] => 4
        [child_guests] => 0
        [company] => gravitate
        [titlename] => 
        [firstname] => John
        [surname] => Doe
        [address1] => 123 Fake St
        [address2] => 
        [city] => New York
        [state] => NY
        [postcode] => 12345
        [country] => US
        [phone] => 1111111111
        [mobile] => 
        [fax] => 
        [email] => [email protected]
        [comments] => 
        [created] => 2011-10-18 13:40:47
        [updated] => 2011-10-18 13:40:47
        [status] => 1
        [cancelled] => 0
        [request_src] => website
        [request_token] => 0
        [token] => ayzrGnx
        [survey_sent] => 0000-00-00 00:00:00
        [survey_returned] => 0000-00-00 00:00:00
        [send_sms] => 0
        [payment_time] => 0000-00-00 00:00:00
        [fullname] =>  John Doe
    )

采纳答案by DaveRandom

I suspect it may contain (bool) FALSE, which is not true for is_null().

我怀疑它可能包含(bool) FALSE,但对于is_null().

Try simply:

简单地尝试:

if ($book['Booking']['comments']) {

This should also work for anything that evaluates to FALSE, like an empty string.

这也适用于任何评估为 的内容FALSE,例如空字符串。

回答by Nathan Loding

if (count($book['Booking']['comments']) > 0) { ... }

if (count($book['Booking']['comments']) > 0) { ... }

回答by Your Common Sense

your question is too localized. There is some typo in your code or something like that.

你的问题太本地化了。您的代码中有一些错字或类似的东西。

There is absolutely no differencewhat to use in your case, if (!empty($var))or if ($var). So, if ($book['Booking']['comments']) {worked, there was no problem with your if (!empty($book['Booking']['comments']))too. So, there was no poin in the question at all.

在您的情况下使用什么绝对没有区别if (!empty($var))或者if ($var). 所以,if ($book['Booking']['comments']) {工作,你if (!empty($book['Booking']['comments']))也没有问题。所以,这个问题根本没有任何意义。

All these answers trying to answer this not-a-real-question are nonsense.

所有这些试图回答这个非真实问题的答案都是无稽之谈。

the only issue can be a space symbol mentioned by jotorres1, but you have already said there are none.

唯一的问题可能是 jotorres1 提到的空格符号,但您已经说过没有。

回答by Elte Hupkes

!empty($var), count($var) > 0, !$var, all of these will work in most situations. empty() has the "advantage" of not throwing a notice when the given variable / array key doesn't exist, but if you don't have to worry about that a boolean check (!$var) should suffice (see herewhich types convert to FALSE). It also happens to be the shortest in code.

!empty($var), count($var) > 0, !$var, 所有这些都适用于大多数情况。empty() 具有在给定变量/数组键不存在时不抛出通知的“优势”,但如果您不必担心布尔检查 ( !$var) 就足够了(请参阅此处哪些类型转换为错误的)。它也恰好是代码中最短的。

回答by hex4

that is not an array for sure.

这肯定不是一个数组。

do var_dump($book["Booking"]["comments"])to check the data type accordingly

做相应var_dump($book["Booking"]["comments"])地检查数据类型

回答by jotorres1

I think you can try to use this following logic, and try to make it a little bit simpler.

我认为你可以尝试使用以下逻辑,并尝试使其更简单一些。

<?php 
    // Only change this
    // and leave everything else as is
    $book_comment = $book['Booking']['comments'];
    $book_comment = trim($book_comment);
    // The reason I use empty trim, is to take 
    // away any space.  
    // In the output, use the original $book['Booking']['comments']

    if(!empty($book_comment)):?>

      <table width="100%" border="0">
          <tbody>
              <tr>
                  <td style="font-family:'Lucida Grande', sans-serif;font-size:12px;font-weight:normal;color:#666666;">
                      <?=$book['Booking']['comments']?>
                  </td>
              </tr>
          </tbody>
       </table>
<?php endif;?>

I have not tested this, as I can't right now, but hopefully that should somewhat help you.

我还没有测试过这个,因为我现在不能,但希望这能对你有所帮助。

回答by leo.vingi

I don't think that $book['Booking']['comments']is even an array in this case. So you could just use strlenhttp://php.net/manual/en/function.strlen.php

$book['Booking']['comments']在这种情况下,我认为这甚至不是一个数组。所以你可以使用strlenhttp://php.net/manual/en/function.strlen.php

<?php if (strlen($book['Booking']['comments'])) {?>

<?php if (strlen($book['Booking']['comments'])) {?>

回答by Donnie

You may want to trim()that property to remove any whitespace before testing if it is empty().

您可能希望trim()该属性在测试之前删除任何空格empty()

Edit: I'm assuming it is a string. It doesn't look like an empty array.

编辑:我假设它是一个字符串。它看起来不像一个空数组。

回答by leymannx

  1. Empty array:

    $array = array();

    reset($array)returns FALSE.

  2. Populated array:

    $array = array('foo', 'bar');

    reset($array)returns first element ('foo').

  1. 空数组:

    $array = array();

    reset($array)返回FALSE

  2. 填充数组:

    $array = array('foo', 'bar');

    reset($array)返回第一个元素 ( 'foo')。

回答by Faisal

If you want to ascertain whether the variable you are testing is actually explicitly an not empty array, you could use something like this:

如果你想确定你正在测试的变量是否实际上是一个非空数组,你可以使用这样的东西:

if ($book['Booking']['comments'] !== array()) {
  //your logic goes here
  ....................
}

This logic is more faster from others solution. Also it will maintain coding standard.

这种逻辑从其他解决方案中更快。它还将保持编码标准。