Hello Friends,

Welcome To Infinitbility!

How to Check if value exists in array using indexOf for javascript and in_array for php.

we are going to discuss today’s topic “How to find and specific item on an array without loops in javascript and PHP.”

Let’s begins with Javascript

JavaScript

Javascript provides indexOf function to find value from an array Understand with an example


//indexOf example
var fruits = ['Banana', 'Blackcurrant', 'Blueberry', 'Chili pepper', 'Cranberry', 'Eggplant', 'Gooseberry'];

// You get their index ( Key )
var index = fruits.indexOf('Blueberry');
// output 2

// if value not available
var index = fruits.indexOf('Apple');
// output -1

PHP

Similarly, Php provides in_array function to find value from an array Understand with an example


<?php

# inArray example
$fruits = ['Banana', 'Blackcurrant', 'Blueberry', 'Chili pepper', 'Cranberry', 'Eggplant', 'Gooseberry'];

# You get true or false
$result = in_array("Blueberry", $fruits);
# output true

# if value not available
$result = in_array("Apple", $fruits);
# output false

?>

Thanks for reading…