thairish thairish - 4 months ago 8
PHP Question

PHP - First and last character check

I am trying a check in PHP. What I want is to check:


  • The first character in a string must be a "["

  • The last character in a string must be a "]"



I've written this code (last if statement is what I actually want) to check this but am not getting the result I wanted:

$str = "dfgdfg]";

if($str[0] != '[') {
echo "FIRST NOT EQUAL TO";
}

if(substr($str,-1) != ']') {
echo "SECOND NOT EQUAL TO";
}


if( ($str[0] != '[') && (substr($str,-1) != ']') ) {
echo "COND MET!";
}


If I run this code I thought that the last if statement would execute however, only the first if statement executes. What is wrong with the logic in the last if statement?

Answer

You have the last statement set as "AND - && " and should be an "OR - ||"

if( ($str[0] != '[') || (substr($str,-1) != ']') ) {
echo "COND MET!";
}