- Chapter 3: Using Arrays
- 1 Declaring an Array
- 2 Printing Out an Array
- 3 Eliminating Duplicate Elements
- 4 Enlarging or Shrinking an Array
- 5 Merging Arrays
- 6 Iteratively Processing Elements in an Array
- 7 Accessing the Current Element in an Array
- 8 Accessing Different Areas of an Array
- 9 Searching an Array
- 10 Searching for the Different Elements in Two Arrays
- 11 Randomizing the Elements of an Array
- 12 Determining the Union, Intersection, or Difference Between Two Arrays
- 13 Sorting an Array
- 14 Sorting Sensibly
- 15 Reversing Order
- 16 Perl-Based Array Manipulation Features
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 itemsnot just the first itemthat 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.