-3

I want to check whether the length of $a is 0 or if the length is not 0 then check if it is a numeric value in single IF statement in PHP. I tried this but not working

$a = '23bc';
if((strlen($a)===0 || (strlen($a)>0 && ctype_digit($a))) )
{
    echo 'Good to Go';
}
else
{
    echo 'Bad to Go';
}

I do not want to apply nested conditions here. Is it possible to do it in single IF statement?

I found this question here but this does not answers what I am asking for && (AND) and || (OR) in IF statements

Community
  • 1
  • 1
NoOneSeesMe
  • 65
  • 2
  • 11

1 Answers1

0

It would be nice to know what your script is trying to achieve beyond using a one-liner in an if conditional concerning an empty string or a numeric string. With cytpe_digit() every character must evaluate as a number to qualify as a numeric string. You get a false result with '23bc' because of the 'bc' portion.

One of the problematic aspects with the script is that one don't know which condition results in a true. One or the other conditions could be true or they could both be false.
See demo: http://3v4l.org/8Pchk.

You could rewrite the code making use of a ternary expression to have a one liner which eliminates the if-else construct, as follows:

<?php
$a = '23bc';

if( strlen( $a ) != 0) {
    echo ctype_digit( $a )? "Good to Go\n"  :  "Bad to Go\n";
}  

The following may be more in line with what you're asking. Here's the ultimate one-liner:

<?php
echo ( !strlen($a) || ctype_digit($a) )? "Good to Go\n"  :  "Bad to Go\n";

Because of the strictness of the identity operator === if $a is null, then you you'll see "Bad to Go. You may either test for equality strlen($a) == 0 or you can be more succinct by using the ! operator (boolean NOT). See demo: http://3v4l.org/7cfV0

slevy1
  • 3,797
  • 2
  • 27
  • 33