Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - find if an array contains an element

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?

like image 635
Matthew Avatar asked Aug 05 '10 15:08

Matthew


People also ask

How do you check if a array contains a specific word in PHP?

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.

How do you check if a value exists in an array?

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.

How do you check if value exists in array of objects PHP?

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() .

How do I check if two arrays contain the same element in PHP?

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.


2 Answers

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
}
like image 160
Sarfraz Avatar answered Oct 24 '22 00:10

Sarfraz


It's called in_array() xD

like image 27
Joseph Mansfield Avatar answered Oct 24 '22 02:10

Joseph Mansfield