PHP – Check if strings are valid for the specified encoding using mb_check_encoding()

PHPServer Side ProgrammingProgramming

In PHP, the mb_check_encoding() function is used to check if the given strings are valid for the specified encoding. This function checks if the specified byte stream is valid for the specified encoding.


bool mb_check_encoding(str $value=null, str $encoding=null)

Note: The function will check if the stated byte stream is valid for the stated encoding. And if the given value is an array type, then all the keys and values will validate recursively. It avoids the invalid encoding attack.


mb_check_encoding() accepts two parameters: $value and $encoding.

  • $value− It is used to check the byte stream or array if it is omitted and it checks all the input from the beginning of the request.

  • $encoding− It is used for the expected encoding.

Return Values

mb_get_encoding() returns True on success or False on failure.


 Live Demo

   // Using mb_check_encoding function to check
   //if the strings are valid
   $bool = mb_check_encoding ("Hello world", "ASCII");

   // returns true



Note: The mb_check_encoding() function nullable was not allowed in the previous versions but from PHP 8.0, we can use nullable value and encode. From PHP 7.2, mb_check_encoding function accepts an array as a value, previously it used to support only strings.

Published on 23-Aug-2021 08:18:36