0

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>
6
  • Use var_dump() rather than print_r(), that way you can tell if there are any invisible characters such as spaces in your array values Commented May 12, 2016 at 13:44
  • I think var_export for the entire array might be even better cause this allows to copy/paste the code and make a simple test :) Commented May 12, 2016 at 13:56
  • yes.. I edit it :p Commented May 12, 2016 at 13:59
  • Can you do var_dump($test); Commented May 12, 2016 at 13:59
  • The var_export show the issue.. I have to check 'month</span>' and than it works fine. Commented May 12, 2016 at 14:00

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I edit my question.. Your answer doesn't work for me.
Thank you for the tip var_export()
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.