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

2

I want to do a negation check and then the else hit. How can I do it?

See the example!

<?php

$a = '';


if(!$a && !is_string($a)):
   echo 'False';
else:
   echo 'True';
endif;
    
asked by anonymous 29.08.2015 / 15:56

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) 
    
29.08.2015 / 16:48
4

To give you one more option, the simplest way to do this is:

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

With the trim, to ensure that nothing will go empty:

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

The === operator checks whether the value is identical, ie it compares not only values but types.

    
29.08.2015 / 18:38