ctype_space to check all whitespace character(s)

Check whitespace with ctype_space()

ctype_space() checks whether every character is whitespace such as a space, tab, newline, carriage return, or form feed.

$value = " 	
";
var_dump(ctype_space($value));
$var="\t\r\n"; // All are whitespace character(s)
//$var="   "; //  All are whitespace character(s)
//$var=" ab "; // All or some are NOT whitespace character(s)

if(ctype_space($var)){
	echo "<b>$var</b> All are whitespace character(s)";
}else{ 
	echo " <b>$var</b> All or some are NOT whitespace character(s)";
}
Output
All are whitespace character(s)
Syntax
bool ctype_space ( string $input_string )
$input_string : String to be checked.

ctype_space() is a PHP filter function checks the presence of whitespace character(s) in the $input_string . Any thing other than this if present then it return FALSE.

$str = array('string1' => "\n\t\r", 'string2' => "Hello World", 'string3' => "asd\n\r\t",'string4' => 45);
foreach ($str as $val => $string) {
if (ctype_space($string)) {
 echo "<p class='text-success'>The string <b>$val</b> consists of all  whitespace character(s)</p>";
}else {
 echo "<p class='text-danger'>The string <b>$val</b>  consist of non-whitespace character(s)</p>";
 }
}
Output is here

The string string1 consists of all whitespace character(s)

The string string2 consist of non-whitespace character(s)

The string string3 consist of non-whitespace character(s)

The string string4 consist of non-whitespace character(s)


Example: Validating Whitespace Input

$input = "   ";
if (ctype_space($input)) {
    echo "Input is all whitespace.";
} else {
    echo "Input contains non-whitespace characters.";
}
Output
Input is all whitespace.

Example: Handling Empty Strings

$empty_str = "";
if (ctype_space($empty_str)) {
    echo "Empty string treated as whitespace.";
} else {
    echo "Empty string not treated as whitespace.";
}
Output
Empty string not treated as whitespace.

Example: Comparing ctype_space() and trim()

$input = "  text  ";
echo ctype_space($input) ? "Only whitespace" : "Contains non-whitespace";
echo '<br>';
// This will return false because the string contains "text"
if(trim($input)){
echo trim($input); // text
Explanation:
Whitespace Validation: Demonstrates checking if a string contains only whitespace characters.
Empty Strings: Shows that `ctype_space()` returns false for empty strings.
Difference from `trim(): Highlights the functional difference between removing spaces with `trim()` and checking for spaces with `ctype_space()`.
Check for only alphabetic characters by ctype_alpha() Check for all lower or upper Check for at least one lower case or upper case
ctype()



Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer