w3resource
w3resource logo

PHP Array Exercises : Search a specified value within the values of an associative array

(追記) (追記ここまで)
(追記) (追記ここまで)

33. Search Value Within Associative Array

Write a PHP function to search a specified value within the values of an associative array.

Sample Solution:

PHP Code:

<?php
// Define a function named arraysearch that searches for a string in array values
function arraysearch($arra1, $search)
{
 // Reset the array pointer to the beginning
 reset($arra1);
 // Iterate through the array using a while loop
 while (list($key, $val) = each($arra1)) 
 {
 // Check if the search string is found (case-insensitive) in the current array value
 if (preg_match("/$search/i", $val)) 
 {
 // Display a message indicating the search string is found in the current key
 echo $search . " has found in " . $key . "\n";
 } 
 else 
 {
 // Display a message indicating the search string is not found in the current key
 echo $search . " has not found in " . $key . "\n";
 }
 }
}
// Define an associative array of exercises
$exercises = array("part1" => "PHP array", "part2" => "PHP String", "part3" => "PHP Math");
// Call the arraysearch function to search for "Math" in the values of the exercises array
arraysearch($exercises, "Math");
?>

Output:

Math has not found in part1 
Math has not found in part2 
Math has found in part3 

Flowchart:

Flowchart: PHP - Search a specified value within the values of an associative array

For more Practice: Solve these Related Problems:

  • Write a PHP function to search for a specified value in an associative array and return the corresponding key if found.
  • Write a PHP script to iterate over an associative array and output a message if the specified value is present.
  • Write a PHP program to use array_search() to look up a value in an associative array and then display its key.
  • Write a PHP script to implement a case-insensitive search for a value in an associative array and return the result.

Go to:


PREV : Get File Extension.
NEXT : Sort Associative Array (Case-Sensitive by Values).

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

(追記) (追記ここまで)


(追記) (追記ここまで)
(追記) (追記ここまで)


AltStyle によって変換されたページ (->オリジナル) /