Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if an array only contains the listed values in PHP

$array = ['red', 'orange'];

How can I check if this array contains only the values red or orange ?

Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

$array = ['red', 'orange'];

if (empty(array_diff($array, ['red', 'orange']))) {
  echo "The array contains only red and orange.";
} else {
  echo "The array contains other values besides red and orange.";
}

How about using array_diff() function to compare your array with an array that contains only the values "red" and "orange". If the result is an empty array, it means that your original array only contains those values.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading