I have an array with just a list of ids, like so:
$my_array = array(
12, 17, 99, 23
);
Now I know I could probably do something like:
function in_array($haystack = array(), $needle = NULL)
{
foreach($haystack as $id)
{
if ($id == $needle)
{return TRUE;}
else
{return FALSE;}
}
}
but it seems like there's probably already a function built. What could I use?
PHP in_array() Function The in_array() function searches an array for a specific value. Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.
You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.
The function in_array() returns true if an item exists in an array. You can also use the function array_search() to get the key of a specific item in an array. In PHP 5.5 and later you can use array_column() in conjunction with array_search() .
The array_intersect() function compares the values of two (or more) arrays, and returns the matches. This function compares the values of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.
No need to create one, it is already there co-incidentally with the same name you are using: in_array
too.
Example:
if (in_array('foo', $array)){
// foo is in the array
}
It's called in_array() xD
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With