How to search a string or array in another array in php
How to search a string or array in another array in php
In this post snipped I will be showing you how to easily search for a string or an array directly in another array in php really fast and easy with step by step examples.
Scenario
We have the bellow array with our persons names:
1 2 3 |
<?php $persons_array = array("car","cat","Andrew","food","Anthony","melon","juice"); ?> |
Solution
The easiest solution to find a string in your little array is by using the core function in_array()
1 2 3 4 5 6 |
<?php $persons_array = array("car","cat","Andrew","food","Anthony","melon","juice"); if(in_array("Andrew",$persons_array)) { echo "We have Andrew!"; } ?> |
Output
The output will be a simpler message in case the string “car” is found:
1 |
We have a Andrew! |
Scenario 2
Now what if we think about going a bit more advance, searching an array inside another array? We have the following array:
1 2 3 |
<?php $main_array=array("car",array("year","brand","horsepower"),array("food","water")); ?> |
Right? A bit more advance than before. Lets say we want to do something in case we have an array match in our $main_array?
Solution
We will use the same core function, the usage is really the same, just the needle for what we are looking for will be actually an array than a string.
1 2 3 4 5 6 |
<?php $main_array=array("car",array("year","brand","horsepower"),array("food","water")); if (in_array(array('food', 'water'), $main_array, true)) { echo "'Food' and 'Water' has been found!"; } ?> |
Output
The above will search directly for the array in that exact form, the output in our little example will look like:
1 |
'Food' and 'Water' has been found! |
That’s about it, I think you got the idea of how to use this function in your projects. From here you can do some pretty advance things, although I really recommend making yourself a separate method for these searches. I’ll probably show you how to make something similar in one of our next post snipped.