Search code examples
phpstringreturn

PHP - How to check if string have 0 and 1 or 0 or 1


I have this function:

function return_a_number($source) {
  switch ($source) {
    case "0&0&0&0":
      return 0;
    case "0&0&1&1":
      return 1;
    case "1&1&1&1":
      return 2;
  }
}

Where $source have an ipotetic number concatenated with &.

How can i return 0 if $source have only '0' characters or 1 if have '0' and '1' characters or 2 if have only '1' characters?


Solution

  • // If there is a 0, ( check if there's also a one -> 1 or 0 ) : else only 1s => 2
    return strpos($source, '0') !== false ? ( strpos($source, '1') !== false ? 1 : 0 ) : 2;
    

    You could of course also write a regex, but why make it complicated if it works that simple. You might want to catch an empty string depending on your input.