comparing multiple values against in_array

David Carr

PHP & MySQL Tutorials

Table of Contents

PHP's in_array is useful to determine if an item is in an array but when needing to compare multiple values against in_array no results will be found.

A way round this is to loop through the values and compare each one in turn, this function is pefect that that task:

function isInArray($needle, $haystack) 
{
    foreach ($needle as $stack) {
        if (in_array($stack, $haystack)) {
        	return true;
        }
    }
    return false;
}

This function expects 2 arrays to be passed, it will then loop through the keys and compare them. If no matches are found false is returned.

A quick demo

Here are two arrays, the exclude array is a list of people to exclude.

$people = array(
	'Dave', 
	'Emma', 
	'Terry', 
	'Cath'
);

$exclude = array(
	'emma'
);

Using array_map we can make all items lowercase so case sensativity does not get in the way.

$people = array_map('strtolower', $people);
$exclude = array_map('strtolower', $exclude);

Check if any person from the excludes array is in the people array.

if(isInArray($exclude, $people) == true){
	echo 'people from excludes are in the array $people';
} else {
	echo 'no exclusions';
}

Putting it together

function isInArray($needle, $haystack) 
{
    foreach ($needle as $stack) {
        if (in_array($stack, $haystack)) {
        	return true;
        }
    }
    return false;
}

$people = array(
	'Dave', 
	'Emma', 
	'Terry', 
	'Cath'
);

$exclude = array(
	'emma'
);

$people = array_map('strtolower', $people);
$exclude = array_map('strtolower', $exclude);

if(isInArray($exclude, $people) == true){
	echo 'people from excludes are in the array $people';
} else {
	echo 'no exclusions';
}

 

Fathom Analytics $10 discount on your first invoice using this link

David Carr - Laravel Developer

Hi, I’m David Carr

A Senior Developer at Vivedia
I love to use the TALL stack (Tailwind CSS, Alpine.js, Laravel, and Laravel Livewire)

I enjoy writing tutorials and working on Open Source packages.

I also write books. I'm writing a new book Laravel Testing Cookbook, This book focuses on testing coving both PestPHP and PHPUnit.

Sponsor me on GitHub

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Laravel Testing Cookbook

Help support the blog so that I can continue creating new content!

Fathom Analytics $10 discount on your first invoice using this link

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2006 - 2023 DC Blog. All code MIT license. All rights reserved.