php

Check if value exist in array using in_array() PHP

You can check if a value exists in the given array or not using PHP inbuilt function in_array().

<?php
    $subjects = ["Math", "Physics", "Chemistry", "English", 50];
    
    //WITHOUT TYPE CHECK
    if (in_array("Chemistry", $subjects)) {
        echo "value exists";
    } else {
        echo "value does not exist";
    }

    //WITH TYPE CHECK - will check for string type 50
    if (in_array("50", $subjects, TRUE)) {
        echo "value exists";
    } else {
        echo "value does not exist";
    }
?>

in_array() function takes two required parameter $value and $array and one Optional parameter $type_check

Syntex - in_array($value, $array, $type)

$value: This is a required parameter that is checked against the array if it exists in the array or not.

$array: This is also a required parameter. This is the array that contains a set of values.

$type: This is an optional parameter and it determines whether the value should be matched with its data type or not. If you want the value to be matched with its type you can pass TRUE in this parameter.

Was this helpful?