...

View Full Version : Resolved In_Array Always True?



RonnyNishimoto
07-18-2012, 02:26 AM
Why won't this work? For some reason, $checking is always coming up true and it's just echoing $search. It works when I put in_array within the if() statement, but is there a way to keep it outside?



<?php
$text = array("blah", "blah2", "blah3");
$checking = in_array("not-in-array", $text);
if ($checking = 1) {
echo "This shouldn't appear.";
}
else {
echo "There are no results!";
}
?>


I'm using this for this, even when I change $search to something random, it still comes out to be true:



<?php
$text = array("blah", "blah2", "blah3");
$search = $text['0'];
$checking = in_array($search, $text);
if ($checking = 1) {
echo $search;
}
else {
echo "There are no results!";
}
?>

Keleth
07-18-2012, 02:51 AM
if ($checking = 1) {

This is not checking if $checking is 1. This is assigning 1 to $checking (look just one line above where you actually do the assignment. As the assignment is successful, it returns true. It will always be true.

RonnyNishimoto
07-18-2012, 02:54 AM
Wait how can I get this to work?



<?php
$text = array("blah", "blah2", "blah3");
$search = $text['1'];
global $checking;
$checking = in_array($search, $text);
if ($checking = 1) {
echo $search;
}
else {
echo "There are no results!";
}
?>

Cloud Ghost
07-18-2012, 08:21 AM
= Is an assigning operator.
== Is a comparing operator.

You want to compare $checking to 1 and therefore you want to use ==. You could actually just get away with using if ($checking) { as well but that's coder preference.

tangoforce
07-18-2012, 08:41 AM
= Is an assigning operator.
== Is a comparing operator.


+1

PHP does not use the = operator like some other languages.

RonnyNishimoto
07-18-2012, 08:11 PM
:thumbsup:



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum