Jump to content

[SOLVED] Search for values in arrays


vineld

Recommended Posts

Well, when you say "if a number of values all exist within an array" the best answer may be array_diff(), array_diff_assoc(), array_intersect() or array_intersect_assoc(). Your question was a little too vague. Perhaps you could provide a real example of what you are wanting to accomplish.

Maybe I should have made the question a little bit more specific although I will instead make it wider =) More specifically I am thinking about these two scenarios:

 

Array example values: 5, 6, 8, 12, 16, 23, 35

 

Scenario 1:

Finding out if either 5, 8 or 23 exist in the array.

 

Scenario 2:

Finding out if both 5, 8 and 23 exist in the array.

 

In the second case array_diff is definitely the best choice but what about the first? Same and count the result? If the arrays are large this might not be a good idea?

 

In_array is the obvious choice for a single value but I'm not entirely sure of the functionality of in_array when the needle is an array?

I'd agree with mjdamato on this one. Code examples below:

 

<?php
$a = array(5, 6, 8, 12, 16, 23, 35);
$b = array(5, 8, 23);
//$b = array(5, 8, 23,55);	// Shows what happens when a number isnt in $a


// To check to see if some of the values are in the array (Scenario 1):
if(count(array_intersect($b, $a))>0) {
echo count(array_intersect($b, $a)),' elements were from array(5, 8, 23) were in array(5, 6, 8, 12, 16, 23, 35)<br>';
}

// To check to see if all of the values are in the array (Scenario 2):
if(!count(array_diff($b,$a))) {
echo 'All elements from array(5, 8, 23) were in array(5, 6, 8, 12, 16, 23, 35)<br>';
} else {
echo 'You were missing the following: ';
print_r(array_diff($b,$a));
}
?>

I know you are. And you are the only one in this thread who is.

 

Yeah, for a minute there (well, at least a second or two) I thought I was missing something. Here are a couple quick functions you could use building upon what haku posted

function allInArray($needleArray, $haystackArray)
{
    //Returns true or false based on if all the values in the
    //needle array are found inthe haystack array
    return (count(array_diff($needleArray, $haystackArray)) == 0);
}

function someInArray($needleArray, $haystackArray)
{
    //Returns false if no values are found in haystack array
    //or an array of the values found in the haystack array
    $found = array_intersect($needleArray, $haystackArray);
    return (count($found)==0) ? false : $found;
}

 

Not tested

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.