Lets say I have an array called $values I use a series of IF statements to add items to the array using array_push I now want to use an IF statement to check if ANY of the possible items exist in the array. Normally I'd do something like: if (in_array('item1', $values) || in_array('item2', $values) || in_array('item3', $values)) But is there another (simpler) way of doing this? Can I make the list of all possible items and put that in an array or something?
function any_in_array( $items = array(), &$array, $strict = false ) { foreach ( $items as $item ) if ( in_array($item, $array, $strict) ) return true; return false; } function all_in_array( $items = array(), &$array, $strict = false ) { foreach ( $items as $item ) if ( !in_array($item, $array, $strict) ) return false; return true; } PHP: I would assume you want the any_in_array function.
Hmmmm I didn't expect to have to use a function! It would have been good if the "in_array" could take multiple search terms! :-|
The function is just a wrapper, take it out of the function if you like, but it's likely you'll have to do something similar somewhere else in your code, and I'm a supporter of the DRY principle. Dan. Example usage : $items = array('name', 'phone', 'something', 'else'); $values = array('whatever'); if(any_in_array($items, $values)) { /* Do something */ } else { /* Do something else */ } PHP:
There has GOT to be a simpler way of doing this! Something along the lines of: if (in_array('item1' || 'item2' || 'item3', $values)) Obviously that doesn't work but it seems odd that something like this isn't part of the standard PHP functionset!
I got the solution I was looking for! $newItems = array('item1', 'item2', 'item3'); $testArray = array_intersect($values, $newItems); Code (markup): From another forum