0

im sitting with a pretty simple image uploader, where the first image uploaded is going to be treated in a special manner. I then run a loop over all the files, and skip the first image.

For this i have named the first image headImage, and i skip it when it has been moved, and done the other stuff to it.

I have cut out all excess code, and are only displaying the loop causing my problem:

Sorted image array:

array (size=5)
    'headImage' => 
        array (size=5)
            'name' => string '8-skilling-1606-eller-07-54-1-h93a.jpg' (length=38)
            'type' => string 'image/jpeg' (length=10)
            'tmp_name' => string '/tmp/phpNUoAtX' (length=14)
            'error' => int 0
            'size' => int 37748
    0 => 
        array (size=5)
            'name' => string '807003718_2_Big.jpg' (length=19)
            'type' => string 'image/jpeg' (length=10)
            'tmp_name' => string '/tmp/php1TXBdm' (length=14)
            'error' => int 0
            'size' => int 36328

Foreach loop which skips if the fileKey is "headImage", and dumps the fileKey

foreach($uploadFiles as $fileKey => $file){
    if($fileKey == "headImage"){
        var_dump($fileKey);
        continue;
    }
}

And the output from var_dump:

string 'headImage' (length=9)
int 0

Now, why is the if sentence ran when the value of $fileKey clearly isn't "headImage"?

DalekSall
  • 385
  • 1
  • 2
  • 12

2 Answers2

2

Because "string" == 0 in PHP.

You have to compare using type too, try === comparison:

foreach($uploadFiles as $fileKey => $file){
    if($fileKey === "headImage"){
        var_dump($fileKey);
        continue;
    }
}
pavel
  • 26,538
  • 10
  • 45
  • 61
2

best and safe way to compare two string is using php strcmp function

use like this :

foreach($uploadFiles as $fileKey => $file){
    if(strcmp($fileKey ,"headImage") == 0){
        var_dump($fileKey);
        continue;
    }
}

PHP strcmp function Document

Pouya Darabi
  • 2,246
  • 18
  • 23