0
<?php

$honorifics = array("None", "Miss", "Ms.", "Mrs.", "Mr.", " Mx", " Dr.", "Prof.", "Rabbi", "Reverend", "Imam");
?>

<?php foreach ($honorifics as $index => $honor){
        if ($index = 0) {
          continue;
        }
        echo ( $index );
}?>

prints out

00000000

why?

I saw that removing the continue fixes the problem, but thats not what I want. I wan't to understand what's going wrong.

how to fix?

Toskan
  • 13,911
  • 14
  • 95
  • 185

3 Answers3

2
if ($index = 0) {
    continue;
}

store 0 value to $index variable, what you want is if ($index == 0) or, better if (!$index)

In php (and other languages I assume) you can set a variable data in a condition, this is often not what you want ans should be avoided, but sometimes can be useful, take this example:

$len = $query->count()  // mysql query count()

if ($len) {
    // do stuff
}

// this can be shortened to

if ($len = $query->count()) {
    // do stuff if true
    echo $len;  // will echo the actual count()   
}

to avoid errors like this, I usually test my variables like this:

if (0 == $index)

this WILL throw an error if you miss your expression not on purpose :) but nowadays, when using IDE like phpstorm, netbeans or others, generally there is an inspection that warn you about that statement.

EDIT:

Here the inspection to enaable in PHPStorm:

enter image description here

And here the result:

enter image description here

kitensei
  • 2,510
  • 2
  • 42
  • 68
1

You are assigning 0 to $index in every loop and then checking.

if ($index = 0) {

would work same like -

$index = 0;
if($index) { // if(0) {

Which is false and which is perfectly fine. That's why it is not satisfying the condition and $indexis printing 0 in every loop.

It should be -

if ($index === 0) { 
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
0

Please change this:

if ($index = 0) {

to this one:

if ($index == 0) {
Atif Tariq
  • 2,650
  • 27
  • 34