Manual Iteration
While less efficient, in this example, the isBinStr() function iterates through each character of the input string and checks if it is either 0 or 1. If any character is not 0 or 1, the function returns false. Otherwise, it returns true.
Example: This example shows the usage of the above-mentioned approach.
<?php
function isBinStr($str) {
for ($i = 0; $i < strlen($str); $i++) {
if ($str[$i] !== '0' && $str[$i] !== '1') {
return false;
}
}
return true;
}
$str1 = "101010";
$str2 = "123456";
echo isBinStr($str1)
? "The string is binary."
: "The string is not binary.";
echo "\n";
echo isBinStr($str2)
? "The string is binary."
: "The string is not binary.";
?>
Output
The string is binary. The string is not binary.
Check if a given String is Binary String or Not using PHP
Given a String, the task is to check whether the given string is a binary string or not in PHP. A binary string is a string that should only contain the ‘0’ and ‘1’ characters.
Examples:
Input: str = "10111001" Output: The string is binary. Input: str = "123456" Output: The string is not binary.
Table of Content
- Using Regular Expression
- Using strspn( ) Function
- Manual Iteration