Home > Mobile >  Multiple values in array excluding specified key
Multiple values in array excluding specified key

Time:05-31

I'm trying to verify if certain values exist within an array excluding a specific key:

$haystack = array(
    "id" => 1,
    "char1" => 2,
    "char2" => 3,
    "char3" => 4,
);

$needles = array(2, 4);

Solution that I found here: in_array multiple values

function in_array_all($needles, $haystack) {
    return empty(array_diff($needles, $haystack));
}

The problem is that I'm checking if certain chars exist within the array. This will work fine in this case:

$exists = in_array_all([2, 4], $haystack); // true

But it'll cause an issue in this situation:

$exists = in_array_all([1, 3], $haystack); // true

It found the value 1 in the key id and therefor evaluates as true while a char with id 1 is not within the array. How can I make it so that it excludes the key id within the search?

Note: This is example data. The real data is much larger, so just using if / else statements isn't really viable.

CodePudding user response:

function in_array_all($needles, $haystack) {
    return empty(array_diff($needles, $haystack));
}

function excludeKeys($haystack){
    $tempArray = array();
    foreach($haystack as $key => $value){
        if ($key == "id"){
            // Don't include
        }else{
            $tempArray[$key] = $value;
        }
    }
    return $tempArray;
}

$haystack = array(
    "id" => 1,
    "char1" => 2,
    "char2" => 3,
    "char3" => 4,
);

$exists = in_array_all([1, 3], excludeKeys($haystack));

echo("Exists: ".($exists ? "Yes" : "No"));

This basically just returns the array without the keys you specify. This keeps the original array in tact for later use.

Edit:

These bad solutions are really a symptom of a problem in your data structure. You should consider converting your array to an object. It looks like this:

$object = new stdClass();
$object->id = 1;
$object->chars = array(2, 3, 4);

$exists = in_array_all([1, 3], $object->chars);

This is how you're supposed to separate your data up. This way you can properly store your information by key. Furthermore you can store other objects or arrays within the object specific to a key, as shown above.

CodePudding user response:

Unset id index and then do search:

function in_array_all($needles, $haystack) {
   unset($haystack['id']);
   return empty(array_diff($needles, $haystack));
}

https://3v4l.org/CDDcf

  • Related