Appearance
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:
Example of checking if an array element exists in PHP
php
<?php
$fruits = ["apple", "banana"];
if (in_array("apple", $fruits)) {
echo "Apple exists in the array";
} else {
echo "Apple does not exist in the array";
}
<div class="alert alert-info flex not-prose">Watch a video course Learn object oriented PHP
</div>
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.
Example of checking if an array element exists with use array_search() function in PHP
php
<?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";
}