PHP array_search() Function - GeeksforGeeks (2024)

Skip to content

PHP array_search() Function - GeeksforGeeks (1)

Last Updated : 01 Dec, 2021

Improve

Improve

Like Article

Like

Save

Report

In this article, we will see how to search the specific value in an array & corresponding return the key using the array_search() function in PHP, & will also understand its implementation through the examples. The array_search() is an inbuilt function in PHP that is used to search for a particular value in an array, and if the value is found then it returns its corresponding key. If there are more than one values then the key of the first matching value will be returned.

Syntax:

array_search($value, $array, strict_parameter)

Parameters: This function takes three parameters as described below:

  • $value: This is the mandatory field that refers to the value that needs to be searched in the array.
  • $array: This is the mandatory field that refers to the original array, which needs to be searched.
  • strict_parameter (optional): This is an optional field that can be set to TRUE or FALSE, and refers to the strictness of search. The default value of this parameter is FALSE.
    • If TRUE, then the function checks for identical elements, i.e., an integer 10 will be treated differently from a string 10.
    • If FALSE, strictness is not maintained.

Return Value: The function returns the key of the corresponding value that is passed. If not found then FALSE is returned and if there is more than one match, then the first matched key is returned.

Example: The below program illustrates the array_search() function in PHP.

PHP

<?php

// PHP function to illustrate the use of array_search()

function Search($value, $array)

{

return (array_search($value, $array));

}

$array = array(

"ram",

"aakash",

"saran",

"mohan",

"saran"

);

$value = "saran";

print_r(Search($value, $array));

?>

Output:

2

Example: This example illustrates the working of function when the strict_parameter is set to FALSE. Note that the data types of the array and to be searched elements are different.

PHP

<?php

// PHP function to illustrate the use of array_search()

function Search($value, $array)

{

return (array_search($value, $array, false));

}

$array = array(

45, 5, 1, 22, 22, 10, 10);

$value = "10";

print_r(Search($value, $array));

?>

Output:

5

Example: In this example, we will be utilizing the above code to find out what will happen if we pass the strict_parameter as TRUE.

PHP

<?php

// PHP function to illustrate the use of array_search()

function Search($value, $array)

{

return (array_search($value, $array, true));

}

$array = array(45, 5, 1, 22, 22, 10, 10);

$value = "10";

print_r(Search($value, $array));

?>

Output:

No Output

Reference: http://php.net/manual/en/function.array-search.php



Improve

Please Login to comment...

Similar Reads

How the User-Defined Function differs from Built-in Function in PHP ?

In PHP, functions are blocks of reusable code that perform specific tasks. They enhance code readability, modularity, and maintainability by encapsulating logic into named units. PHP functions can be categorized into two main types: user-defined functions and built-in functions. User-Defined FunctionsUser-defined functions are functions created by

2 min read

PHP 5 vs PHP 7

PHP is a server side scripting language designed for web development by Rasmus Lerdorf in 1994. Since its launch in 1994 PHP has become an industry standard supporting almost 80% of the websites ( 79.8% to be precise) with its closest competitor being ASP.Net at 19.8% and others like Ruby, Java trailing far behind. The PHP development team released

4 min read

PHP | Get PHP configuration information using phpinfo()

PHP provides us with a built-in function phpinfo() which gives us the details about the PHP version and PHP configuration of PHP installed in our system. To know about the Configurations and PHP version which is installed in your computer, a simple PHP script can be used. The script consists of a PHP function called "phpinfo()" which outputs inform

2 min read

How to include content of a PHP file into another PHP file ?

Including the content of a PHP file into another file reduces the complexity of code by reducing the code and improving its modularity by splitting the code into different files so that it is easy to understand and manage. There are two ways to do it by using the following PHP functions. PHP include() Function: It will show the warning if the file

2 min read

What is New in PHP Type Hinting Support in PHP 8?

PHP 8 introduced several enhancements and new features related to type hinting. That will check the code for their respective type so that we can use our code efficiently. These are the following features used in PHP Type Hitting Support: Table of Content Union TypesMixed TypeStatic Return TypeInheritance of Contravariant ParametersInheritance of P

3 min read

PHP | imagecreatetruecolor() Function

The imagecreatetruecolor() function is an inbuilt function in PHP which is used to create a new true-color image. This function returns a blank image of the given size. Syntax: resource imagecreatetruecolor( $width, $height ) Parameters: This function accepts two parameters as mentioned above and described below: $width: This parameter is used to s

2 min read

PHP fpassthru( ) Function

The fpassthru() function in PHP is an inbuilt function which is used to read data from a current position from a specified file until end of file and then write the result to the output buffer. The file which has to be read is sent as a parameter to the fpassthru() function and it returns the number of characters passed on success or FALSE on failu

2 min read

PHP | ImagickDraw getTextAlignment() Function

The ImagickDraw::getTextAlignment() function is an inbuilt function in PHP which is used to get the alignment applied when annotating with text. It helps to format the text by making it stick to left, right or middle. Syntax: int ImagickDraw::getTextAlignment( void ) Parameters: This function doesn’t accept any parameter. Return Value: This functio

2 min read

PHP | Ds\Sequence last() Function

The Ds\Sequence::last() function is an inbuilt function in PHP which is used to return the last element from the sequence. Syntax: mixed abstract public Ds\Sequence::last( void ) Parameters: This function does not accept any parameters. Return value: This function returns the last element from the sequence. Below programs illustrate the Ds\Sequence

1 min read

PHP | array_udiff_uassoc() Function

The array_udiff_uassoc() Function is an inbuilt function in PHP and is used for distinguishing between two or more array. The function computes the differences array by use of two user-defined functions with the additional index key. It compares both data and index by use of callback functions and returns the difference. Syntax : array_udiff_uassoc

5 min read

PHP array_search() Function - GeeksforGeeks (2)

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

PHP array_search() Function - GeeksforGeeks (3)

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `

${comment_text}

`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); jQuery('.suggest-bottom-btn').on('click', function(){ var suggest_val = $.trim($("#suggestion-section-textarea").val()); var error_msg = false; if(suggest_val != ""){ if(suggest_val.length <= 2000){ jQuery('body').append('

'); jQuery('.spinner-loading-overlay').show(); jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify({ "gfg_post_id" : `${post_id}`, "suggestion" : `

${suggest_val}

` }), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').html("Sent "); setTimeout(() => { jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); }, 1000); }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('#suggestion-modal-alert').html("Character limit exceeded."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('#suggestion-modal-alert').html("Enter valid input."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } }) $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('

'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });

PHP array_search() Function - GeeksforGeeks (2024)
Top Articles
Latest Posts
Article information

Author: Duncan Muller

Last Updated:

Views: 6590

Rating: 4.9 / 5 (79 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Duncan Muller

Birthday: 1997-01-13

Address: Apt. 505 914 Phillip Crossroad, O'Konborough, NV 62411

Phone: +8555305800947

Job: Construction Agent

Hobby: Shopping, Table tennis, Snowboarding, Rafting, Motor sports, Homebrewing, Taxidermy

Introduction: My name is Duncan Muller, I am a enchanting, good, gentle, modern, tasty, nice, elegant person who loves writing and wants to share my knowledge and understanding with you.