Domanda

I'm having this piece of the code, where there is a string that can contain both alphabet characters or digits and i need to tell them apart. Wouldn't it be logic to use the function ord()? Sure it would!

    $r_1 = $_POST["r1"];

    $reag_1 = explode (" ", $r_1);

    foreach ($reag_1 as $k => $v) {

      if ( ord($v) != (48 || 49 || 50 || 51 || 52 || 53 || 54 || 55 || 56 || 57)){

      // if its a digit then do some stuff

      } else {

      // then its something else and lets do some OTHER stuff

      }
    }

Now the funny thing is that whatever I feed to an $reag_1 seems to go only to true path. I double checked var_dump()-ed the $reag_1 and traced where the program goes. There are alphabetic characters in that array. Where is my mistake that doesn't let the algorithm to go the proper way? I have a feeling I keep making a very basic syntax error.

Thanks in advance!

È stato utile?

Soluzione

Use (ord($v)>=48) and (ord($v)<=57).

You can even use >=Ord("0") and <=Ord("9").

There is even is_numeric function.

Altri suggerimenti

Probably, this line is not logically correct in PHP:

if ( ord($reag_1[$k]) != (48 || 49 || 50 || 51 || 52 || 53 || 54 || 55 || 56 || 57))

You must use:

if(ord($reag_1[$k]) != 48 || ord($reag_1[$k]) != 49 ...)

or better way to use:

$array = array(48, 49, 50, 51, 52, 53, 54, 55, 56, 57)
if(in_array(ord($reag_1[$k]), $array)){
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top