I’ve got a script and simple if check to see if a value is in a array. I can’t seem to find out why the if tag runs when it’s in the array.
else if (!in_array($type, $avatarformats)) {
$error .= '<div class="alert error">You\'re image is not a allowed format</div>';
unlink($_FILES['file']['tmp_name']);
}
When the script reads $type and $avatarformats it’s = to the following.
$avatarformats = Array ( [0] => .jpg [1] => .jpeg [2] => .png )
$type = .png
The if tag runs when it should not because .png is in the array. Or am I no understaind what am doing.
I suspect that
in_array()is returning true because the statement!in_array($type, $avatarformats)is evaluating to true due to the full stop. It is evaluating the value of$typeas an integer because of the decimal place.That being said you have 2 options:
1) Try stripping the dot i.e. “.png” to “png” from the file extension before adding it to the array in the first place and then do the test.
2) or change your conditional to the following:
else if (in_array($type, $avatarformats) == false) {in_array()is a strange beast and I try to avoid it at the best of times. isset() is your friend and much faster than in_array under most conditions anyways.