In this PHP tutorial, you shall learn how to check if given string contains only uppercase letters using ctype_upper() function, with example programs.

PHP – Check if string contains only uppercase letters

To check if a string contains only uppercase letters in PHP, call ctype_upper() function and pass given string as argument.

The ctype_upper() function returns a boolean value representing of the situation: if the string contains only uppercase characters.

Syntax

The syntax to check if string str contains only uppercase letters is

ctype_upper($str)

The above expression returns a boolean value of true if the string $str contains only uppercase characters, or false otherwise.

ADVERTISEMENT

Examples

1. Positive Scenario – String contains only uppercase

In this example, we take a string in str such that it contains only uppercase characters. For the given value of string, ctype_upper() returns true and if-block executes.

PHP Program

<?php
  $str = 'APPLE';
  if ( ctype_upper($str) ) {
    echo 'string contains only uppercase';
  } else {
    echo 'string does not contain only uppercase';
  }
?>

Output

2. Negative Scenario – String contains lowercase also

In this example, we take a string in str such that it contains some lowercase letters also, along with uppercase letters. For the given value of string, ctype_upper() returns false and else-block executes.

PHP Program

<?php
  $str = 'APPle';
  if ( ctype_upper($str) ) {
    echo 'string contains only uppercase';
  } else {
    echo 'string does not contain only uppercase';
  }
?>

Output

3. Negative Scenario – String contains digits also

In this example, we take a string in str such that it contains digits also, along with uppercase letters. For the given value of string, ctype_upper() returns false and else-block executes.

PHP Program

<?php
  $str = 'APPLE123';
  if ( ctype_upper($str) ) {
    echo 'string contains only uppercase';
  } else {
    echo 'string does not contain only uppercase';
  }
?>

Output

Conclusion

In this PHP Tutorial, we learned how to check if given string contains only uppercase characters, using ctype_upper() function, with the help of examples.