Keys with 'array_search'
Part of the Logic & Flow section of Coddy's PHP journey — lesson 18 of 68.
While in_array() tells you whether a value exists in an array, sometimes you need to know exactly where that value is located. The array_search() function finds a specific value in an array and returns its corresponding key or index.
Here's how it works:
<?php
$players = ["Alice", "Bob", "Charlie", "Diana"];
$position = array_search("Charlie", $players);
echo $position; // Outputs: 2
?>The function takes two parameters: the value you're searching for and the array to search in. When the value is found, array_search() returns the key (for indexed arrays, this is the numeric position starting from 0).
However, there's an important distinction in what gets returned. If the value is found, you get the key. If the value is not found, the function returns false:
<?php
$scores = [95, 87, 92, 78];
$found = array_search(92, $scores); // Returns: 2
$notFound = array_search(100, $scores); // Returns: false
?>This function is particularly useful when you need to determine the position or ranking of an item, such as finding where a player ranks in a leaderboard or locating the index of a specific element for further processing.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyYou will receive two inputs: an array of product names in JSON format and a product name to search for. Read both inputs, convert the JSON string to an array, use array_search() to find the position of the product in the array, and print the result. If the product is found, print its index position. If the product is not found, print "Product not found".
Input format: Two lines - first line contains a JSON array (example: ["laptop","mouse","keyboard","monitor"]), second line contains the product name to search for
Expected output: Either the numeric index position of the product (starting from 0) or the text "Product not found" if the product doesn't exist in the array
Cheat sheet
The array_search() function finds a specific value in an array and returns its corresponding key or index:
<?php
$players = ["Alice", "Bob", "Charlie", "Diana"];
$position = array_search("Charlie", $players);
echo $position; // Outputs: 2
?>The function takes two parameters: the value you're searching for and the array to search in. It returns the key if found, or false if not found:
<?php
$scores = [95, 87, 92, 78];
$found = array_search(92, $scores); // Returns: 2
$notFound = array_search(100, $scores); // Returns: false
?>Try it yourself
<?php
// Read the JSON array input
$jsonInput = fgets(STDIN);
$products = (array)json_decode($jsonInput, true);
// Read the product name to search for
$searchProduct = trim(fgets(STDIN));
// TODO: Write your code below
// Use array_search() to find the product position
// Output the result
echo $result;
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Functions
Anonymous FunctionsClosures and 'use'Arrow FunctionsCallback FunctionsUsing 'call_user_func'Variable FunctionsPassing by ReferenceRecursive FunctionsRecap: Function Medley4Multi-dimensional Arrays
Creating a 2D ArrayAccessing 2D Array ElementsModifying 2D Array ElementsIterating with Nested Loops2D Associative ArraysRecap: Simple Grid Exercise2Advanced Array Manipulations
Adding with 'array_push'Removing with 'array_pop'Adding with 'array_unshift'Removing with 'array_shift'Merging Indexed ArraysMerging Associative ArraysExtracting with 'array_slice'Values with 'in_array'Keys with 'array_search'Recap: Playlist Exercise3Sorting Arrays
Sort Indexed Arrays AscendingSort Indexed Arrays DescendingSort Assoc Arrays by ValueSort Assoc Arrays by KeyNatural Order SortingCustom Sorting with 'usort'Recap: Leaderboard Sorting