How can I check if an array element exists?

In PHP, you can use the "in_array" function to check if an element exists in an array. The function takes two parameters: the value you want to search for, and the array you want to search in. It returns a boolean value indicating whether the value was found in the array or not.

For example, if you have an array called $fruits and you want to check if it contains the value "apple", you would use the following code:

<?php

$fruits = ["apple", "banana"];
if (in_array("apple", $fruits)) {
  echo "Apple exists in the array";
} else {
  echo "Apple does not exist in the array";
}

Watch a course Learn object oriented PHP

You can also use array_search() function to check if element exist in array, this function return the key of the element if exist in array otherwise false.

<?php

$fruits = ["apple", "banana"];
$key = array_search("apple", $fruits);
if ($key !== false) {
  echo "Apple exists in the array";
} else {
  echo "Apple does not exist in the array";
}