Introduction to PHP – Array Functions Part 4

Guest Posts Paolo Nikko Nuñal

Having arrays that have many elements can be a daunting task, most especially if you are going to loop through many elements. However, PHP makes it easier thanks to PHP's multitude of Array functions that includes the arraykeyexist() that searches for an array and the in_array() method that searches for the value in an array.

Here's how you can do it.

Syntax:

array_key_exists([KEY],[ARRAY])


Key - The array key you want to search.

Array - The arrayyou wish to add.

The arraykeyexist() method is useful if you are dealing with associative arrays. These arrays have keys in which the function can use to search and return a boolean if the key exists or not.

<?php

$model =array("Sony"=>"Xperia Z1","Samsung"=>"Note 3","Google"=>"Nexus 5");
$result = (array_key_exists("Apple",$model));
echo var_dump($result);
?>


The following code will return a false, since 'Apple' does not exists on the array.

The other one, is in_array() method that searches for the value rather than the key.

Syntax:

in_array([SEARCH],[ARRAY],[TYPE])


Search- The item that you need to search for.

Array - The array you wish to search for.

Type - (Optional) If set to true, searches for the search-string and specific type in the array.

<?php
$model =array("Sony"=>"Xperia Z1","Samsung"=>"Note 3","Google"=>"Nexus 5");
$result = (in_array("Xperia Z1",$model));
echo var_dump($result);
?>


The code above will return a boolean true, since there is an 'Xperia Z1' model found in the array.