Reputation: 17
I have a situation where i have to ignore empty data when processing the set of string. Some of the string are valid and some comes with just white spaces (created using spacebar in keyboard)
for example the data would come like this in the program...
$x = " ";
In this case i have to tell this $x is empty though there are two white spaces in it.
I tried using PHP empty() function but it returns false. i tried PHP trim() function but it does not help to remove this empty white spaces for the variable to become empty.
How can i get this validated as empty in PHP ?
Upvotes: 1
Views: 1113
Reputation: 17556
You can also write a custom function for check possible multiple white-spaces.
$str = " ";
function isOnlyWhitespace($str) {
return strlen($str) === substr_count($str, ' ') ? true : false;
}
echo isOnlyWhitespace($str); // 1
Upvotes: 0
Reputation: 43904
trim()
removes all the whitespaces from the beginning and end of a string and returns the trimmed string
So you'll need to feed the returned string of trim()
to empty()
:
<?php
$x = " ";
var_dump(empty($x)); // false
var_dump(trim($x)); // string(0) ""
var_dump(empty(trim($x))); // true
Upvotes: 1