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
quick question
Moderator: General Moderators
-
ibanez270dx
- Forum Commoner
- Posts: 74
- Joined: Thu Jul 27, 2006 12:06 pm
- Location: Everywhere, California
- Kieran Huggins
- DevNet Master
- Posts: 3635
- Joined: Wed Dec 06, 2006 4:14 pm
- Location: Toronto, Canada
- Contact:
Re: quick question
Code: Select all
// untested
$numeric_array = array_filter($myarray,'is_numeric');
$non_numeric_array = array_diff($myarray,$numeric_array);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
}
}Code: Select all
foreach ($myarray as $val){
if(is_numeric($val)){
// do something with numbers
}else{
// string time
}
}Re: quick question
Maybe using a callback would be the thing for you - http://il.php.net/manual/en/function.array-map.php
- superdezign
- DevNet Master
- Posts: 4135
- Joined: Sat Jan 20, 2007 11:06 pm
Re: quick question
By the way, ctype_digit() would be the function that you are after, as is_numeric() has a slightly different functionality.
- Kieran Huggins
- DevNet Master
- Posts: 3635
- Joined: Wed Dec 06, 2006 4:14 pm
- Location: Toronto, Canada
- Contact:
Re: quick question
indeed.
a caveat: in_numeric() will validate numbers with decimal points, whereas ctype_xdigit() will not.
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
thanks, I ended up figuring out some PHP regular expressions, which works great.
Thanks again,
- Jeff
Thanks again,
- Jeff