cgee
cgee

Reputation: 1897

checking array value with if statement always returns (output) 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>

Upvotes: 0

Views: 38

Answers (2)

Victor Smirnov
Victor Smirnov

Reputation: 3780

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.

Upvotes: 1

Xyz
Xyz

Reputation: 6013

Well, this seems to be a problem...

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

month is not 12 characters long. You probably have some non-printable characters in that string apart from month

Upvotes: 0

Related Questions