How can I do a validation to check if a variable is empty and is a string in php

Asked

Viewed 198 times

2

I want to do a denial check and then else the fix. How can I?

Take the example!

<?php

$a = '';


if(!$a && !is_string($a)):
   echo 'False';
else:
   echo 'True';
endif;
  • 3

    Saul, to check if the variable is empty use the function empty() and to check if it is a string use ìs_string() both returns are boolean.

  • If you do the check $a == '' not enough to know if it’s empty and string?

2 answers

4


Saul, you can also create a function

<?php

function emptyAndString(&$var)
{
    $var = trim($var);
    return empty($var) && is_string($var);
}

$v = 'Valor';
var_dump(emptyAndString($v));
// bool(false) 

$v = '  ';
var_dump(emptyAndString($v));
// bool(false) 

$v = '';
var_dump(emptyAndString($v));
// bool(true) 
  • Thank you very much, solved!

4

To leave one more option, the simplest way to do it is like this:

if ($string === '') {
}

With Trim, to make sure nothing goes empty:

if (trim($string) === '') {
}

The operator === checks if the value is identical, that is, compares not only the values, but the types.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.