quick question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ibanez270dx
Forum Commoner
Posts: 74
Joined: Thu Jul 27, 2006 12:06 pm
Location: Everywhere, California

quick question

Post 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
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: quick question

Post 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.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: quick question

Post by Eran »

Maybe using a callback would be the thing for you - http://il.php.net/manual/en/function.array-map.php
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: quick question

Post by superdezign »

By the way, ctype_digit() would be the function that you are after, as is_numeric() has a slightly different functionality.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: quick question

Post by Kieran Huggins »

indeed.

a caveat: in_numeric() will validate numbers with decimal points, whereas ctype_xdigit() will not.
ibanez270dx
Forum Commoner
Posts: 74
Joined: Thu Jul 27, 2006 12:06 pm
Location: Everywhere, California

Re: quick question

Post by ibanez270dx »

thanks, I ended up figuring out some PHP regular expressions, which works great.

Thanks again,
- Jeff
Post Reply