0

I have problem with 0th array element as output of FOR cycles. I want server to print letters A B C D E; and if something is different as element in array, than it should be printed something else. So I made conditions and switch statement for that.

But 0th element of array is always printed out as different element. I do not know what I am doing wrong. Can you please help me? Can you explain me why is this happening?

<?php
    $array = array(0,1,2,3,4,"something");
    for($i=0;$i<count($array);$i++){
        echo '<br>'.$i;
        if ($array[$i] == 'something') {
            echo ' something ';
        } else {
            switch ($array[$i])
                {   case "0":
                        echo ' A';
                        break;
                    case "1":
                        echo ' B';
                        break;
                    case "2":
                        echo ' C';
                        break;
                    case "3":
                        echo ' D';
                        break;
                    case "4":
                        echo ' E';
                        break;
                    default:;
                };
            };
        };
    ?>

My output is this:

0 something 
1 B
2 C
3 D
4 E
5 something

But I am expecting this:

0 A 
1 B
2 C
3 D
4 E
5 something
3
  • 1
    try adding reset($array) before your loop Commented Oct 13, 2013 at 12:47
  • Most strings are equal to 0 in PHP, use === to stop this. You can test this yourself with var_dump(0 == "hello"); Commented Oct 13, 2013 at 12:52
  • Did you try 0 == 'something' first? Commented Oct 13, 2013 at 12:57

1 Answer 1

6

When comparing integer 0 to string "something" the string is cast as integer. See:

var_dump((int) 0); // yields int 0
var_dump((int) 'something'); // yields int 0

See PHP bug request 39579. Note, this is NOT a bug, and works as "expected."

The proper comparison should use strict equality (3 equal signs which test both the value and the type):

if ($array[$i] === 'something') {
    echo ' something ';
}

Alternatively, you may cast the "known/assumed" type during the comparison temporarily and still maintain loose equality:

if ((string) $array[$i] == 'something') {
    echo ' something ';
}

// OR with strval

if (strval($array[$i]) == 'something') {
    echo ' something ';
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you deeper explanation. I will check it out. === works perfectly
accepted but cannot upvote, sorry I do not have reputation for this action.

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.