AppDividend
Latest Code Tutorials

PHP Array Search Example | array_search() Function Tutorial

0

PHP Array Search Example | array_search() Function Tutorial is today’s topic. PHP array_search() function searches an array for a value and returns the key. PHP array_search() function returns the key for value if it is found in the array. It returns FALSE or nothing if it is not found. If the value is found in the array more than once, then the first matching key is returned.

PHP Array Search Example

The syntax of PHP array_search() method is following.

array_search(value,array,strict)

The value parameter is required, and it specifies the value to search for.

The array parameter is required, and it specifies the array to search.

The strict parameter is optional which has two possible values. True or false. When set to true, the number 21 is not the same as the string 21.

See the following example.

<?php

// app.php

$data = ['a' => 'krunal', 
        'b' => 'ankit',
        'd' => 'khushbu', 
        'f' => 'nehal', 
        'c' => 'rushabh', 
        'k' => 'krunal', 
        'n' => 'nehal'];
$key = array_search('ankit', $data);
echo $key."\n";

The output of the above code is following.

PHP Array Search Example

 

So, it has returned the key b which is associated with value ankit.

Now, let’s check the scenario where the value does not exist in the array.

<?php

// app.php

$data = ['a' => 'krunal', 
        'b' => 'ankit',
        'd' => 'khushbu', 
        'f' => 'nehal', 
        'c' => 'rushabh', 
        'k' => 'krunal', 
        'n' => 'nehal'];
$key = array_search('tejas', $data);
print($key);

We get nothing because the value does not exist in the array. So in the newer php version, we get nothing.

Pass the third parameter

Let’s pass the third parameter inside the array_search function and see the output.

<?php

// app.php

$data = ['a' => 'krunal', 
        'b' => 'ankit',
        'd' => '46', 
        'f' => 'nehal', 
        'c' => '19', 
        'k' => 'krunal', 
        'n' => '21'];
$key = array_search(21, $data, true);
print($key);

Here, in the above code, we are passing the 21 parameter as an integer, and inside the $data array, the parameter “21” is a string. So, we will get either false or nothing. If we pass the false as the argument, then the output is following.

<?php

// app.php

$data = ['a' => 'krunal', 
        'b' => 'ankit',
        'd' => '46', 
        'f' => 'nehal', 
        'c' => '19', 
        'k' => 'krunal', 
        'n' => '21'];
$key = array_search(21, $data, false);
print($key."\n");

The output is following.

Pass the third parameter

 

Conclusively, PHP Array Search Example | array_search() Function Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.