How to formulate 'if not' in php?

My students need to enter their class name on my webpage, because that locates them in my excel tables. Some of them enter weird and wonderful things there!

I am not too clear on how to formulate ‘if not’ in php. So far I have:

$classes = array('18BE1', '18BE2', '18BE3');

$class = $_POST['class'];
//First, check if the student entered the class name correctly
       if(in_array($class, $classes)) = false {
       echo " 错误:班号不对! Class name wrong! <br> ";
       echo " Please enter the correct class name. <br>";
       echo " Your details could not be sent. <br>";
       echo " 反回再次试一试! Try again!";
	exit;
}

Will that work? In Python I would just write:

if $class not in $classes:

You should have a select/option menu consisting of the same choices that are in the $classes array, so that only a valid choice can be made.

No, due to bad syntax. The in_array() call is correct, but the if() comparison has two problems, that will both disappear once you simply test the boolean result from the in_array() directly. 1) The closing ) for the if( is in the wrong location, and 2) one = is an assignment operator, two == is a comparison operator. The current code is trying to assign a false value, not compare with a false value. However, don’t compare returned boolean values to true/false values. This misses the point of booleans. Just directly use them in an if() conditional test.

To ‘not’ a boolean value, prepend a !

if(!in_array($class, $classes)) { // if not in array
}
1 Like

Thanks a lot! Works like a dream!

Above answer is 100% correct but In case you dont want to use the exclamation mark then you could write

if(false === in_array($class, $classes)  { // if not in array
}

Watch the === comparison operator. It will ensure that two of the same type will be compared, in this case Boolean values.

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service