Home > Articles

chap3_0672323257

  • Print
  • + Share This

3.9 Searching an Array

You want to find the first array element that passes a predefined test.

Technique

Use a while loop in conjunction with PHP's break statement:

<?php
while ($idx < count ($big_array)) {
  if (preg_match ("/\w/", $big_array[$idx])) {
    $first_element = $big_array[$idx];
    break;
  }
  $idx++;
}
print "The first matching element is $first_element";
?>

Comments

Looping through the array with a while loop to find the first element that meets a predefined criterion is one way to find the first relevant match. Another way is to use the preg_grep() function:

<?php
$first_element = array_shift(preg_grep("/\w/", $big_array));
?>

The preg_grep() method is quicker in terms of programmer efficiency, but it is slower, especially when working on large arrays, and does not allow as much flexibility as the first method.

If you want to find all items—not just the first item—that match a certain criteria you can loop through the different values of the array and test each item or use preg_grep() for coding ease.

A foreach loop:

<?php
foreach ($list as $element) {
  if ($element == $criteria) {
    $matches[] = $elementcriteria;
  }
}
?>

Using preg_grep():

<?php
$matches = preg_grep("/regex/", $list);
?>

The first approach uses a foreach loop to loop through the array and if the item matches the criteria, it is added to the $matches array. The second method uses the preg_grep() function, which searches the array for you, returning an array of the items matching the regular expression. For example:

<?php
$republicans = array ("Senator Orrin Hatch",
           "Governor George W. Bush",
           "Senator John McCain",
           "Gary Bauer",
           "Alan Keyes");

$senators = preg_grep ("/^senator/i", $republicans);
?>

More information on preg_grep() is available in Chapter 5, "Matching Data with Regular Expressions," where we discuss regular expressions in depth.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.