dongshu4755 2016-05-12 13:34
浏览 68
已采纳

用if语句检查数组值总是返回(输出)false(else)

I've following array:

Array
(
    [0] =>  class="amount">€39,00
    [2] =>  class="subscription-details">
    [4] => für
    [5] => 1
    [6] => month
)

I want to check if the sixth element of the value is "month".

I use this code:

print_r($test[6]); //Output month

if($test[6] == 'month'){
    echo 'Alex'; //should output
}else{
    echo 'Ecke'; //will output
}

Why this code will output "Ecke" and not "Alex"?

Edit:

var_dump($test[6]) outputs = string(12)

var_export($test[6]) outputs = 'month'

var_export($test) =

<pre>array (
  0 => '<span',
  1 => 'class="amount">&euro;39,00</span>',
  2 => '<span',
  3 => 'class="subscription-details">',
  4 => 'für',
  5 => '1',
  6 => 'month</span>',
)</pre>
  • 写回答

2条回答 默认 最新

  • dqde43215 2016-05-12 13:47
    关注

    It does output Alex. Here is the simplest test case which almost repeats your code as I understand it.

    <?php
    $test = [
        0 => 'class="amount">€39,00',
        2 => 'class="subscription-details">',
        4 => 'für',
        5 => 1,
        6 => 'month</span>',
    ];
    
    var_dump($test[6]);
    var_export($test[6]);
    
    if (trim(strip_tags($test[6])) == 'month') {
        echo PHP_EOL.'Alex'.PHP_EOL; //should output
    } else {
        echo PHP_EOL.'Ecke'.PHP_EOL; //will output
    }
    

    When I run the script I get

    string(12) "month</span>"
    'month</span>'
    Alex
    

    Can you please show result of the var_export for your array. Most likely you have leading or trailing spaces in the word month. You might want to trim the string before comparing it with 'month'.

    Update: I think you've answered your own question when provided var_dump results. The value in $test[6] is not a month but month</span>

    I've updated the test for this and added strip_tags function. This is just for fun and to show that you can easily remove extra tags.

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

报告相同问题?

悬赏问题

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