Page 1 of 1

quick question

Posted: Wed Jun 11, 2008 6:57 pm
by ibanez270dx
hello,
I am iterating through an array in my PHP script... There are two "types" of values in this array - some are numbers, others are words. I need to be able to filter this quickly and easily, like using regular expressions in Ruby. So, for example, if my array looks like this: $myarray = ["1","administration","it_support","5","10",13","human_resources"] then when I iterate over this I want to do something different for the numbers and names.

Any and all help is appreciated!

Thanks,
-Jeff

Re: quick question

Posted: Wed Jun 11, 2008 7:38 pm
by Kieran Huggins

Code: Select all

// untested
$numeric_array = array_filter($myarray,'is_numeric');
$non_numeric_array = array_diff($myarray,$numeric_array);
Makes you appreciate Ruby, doesn't it?

You could also do something during the iteration like:

Code: Select all

foreach ($myarray as $val){
  switch(TRUE){
    case (is_numeric($val)):
      // do something with numbers
    case (!is_numeric($val)):
      // string time
  }
}
or even just :

Code: Select all

foreach ($myarray as $val){
  if(is_numeric($val)){
    // do something with numbers
  }else{
    // string time
  }
}
but I digress.

Re: quick question

Posted: Wed Jun 11, 2008 7:55 pm
by Eran
Maybe using a callback would be the thing for you - http://il.php.net/manual/en/function.array-map.php

Re: quick question

Posted: Wed Jun 11, 2008 8:59 pm
by superdezign
By the way, ctype_digit() would be the function that you are after, as is_numeric() has a slightly different functionality.

Re: quick question

Posted: Thu Jun 12, 2008 1:51 pm
by Kieran Huggins
indeed.

a caveat: in_numeric() will validate numbers with decimal points, whereas ctype_xdigit() will not.

Re: quick question

Posted: Thu Jun 12, 2008 7:56 pm
by ibanez270dx
thanks, I ended up figuring out some PHP regular expressions, which works great.

Thanks again,
- Jeff