Home arrow PHP arrow Page 4 - Arrays

Locating Array Elements - PHP

Arrays offer an ideal means for storing, manipulating, sorting, and retrieving the kinds of data sets that programmers spend a lot of time working with. PHP supports the array data type. This article explains the array-based features and functions it supports. It is excerpted from the book, Beginning PHP 5 and MySQL: From Novice to Professional, by W. Jason Gilmore (Apress, 2004; ISBN: 1893115518).

  1. Arrays
  2. Outputting Arrays
  3. Testing for an array
  4. Locating Array Elements
  5. Determining Array Size and Uniqueness
  6. Other Useful Array Functions
By: Apress Publishing
Rating: starstarstarstarstar / 37
June 23, 2005

print this article



Often, the value of data can be determined by the ability to easily identify items of value, rather than the amount accumulated. If you arenít able to quickly navigate the information, little good is done accumulating it. In this section, Iíll introduce several functions that enable you to sift through arrays, in an effort to locate items of interest efficiently.


boolean in_array(mixed needle, array haystack [,boolean strict])

The in_array() function searches the haystack array for needle, returning TRUE if found, and FALSE otherwise. The optional third parameter, strict, forces in_array() to also consider type. An example follows:

$grades = array(100,94.7,67,89,100);
if (in_array("100",$grades)) echo "Somebody studied for the test!";
if (in_array("100",$grades,1)) echo "Somebody studied for the test!";


Somebody studied for the test! =====================================================

This string was output only once, because the second test required that the datatypes match. Because the second test compared an integer with a string, the test failed.


array array_keys(array target_array [, mixed search_value])

The array_keys() function returns an array consisting of all keys located in the array target_array. If the optional search_value parameter is included, only keys matching that value will be returned. An example follows:

$state["Delaware"] = "December 7, 1787";
$state["Pennsylvania"] = "December 12, 1787";
$state["New Jersey"] = "December 18, 1787";
$keys = array_keys($state);
// Array ( [0] => Delaware [1] => Pennsylvania [2] => New Jersey )


boolean array_key_exists(mixed key, array target_array)


mixed key(array input_array)

The key() function returns the key element located at the current pointer position of input_array. Consider the following example:

$capitals = array("Ohio" => "Columbus", "Iowa" => "Des Moines","Arizona" => "Phoenix");
echo "<p>Can you name the capitals of these states?</p>";
while($key = key($capitals)) {
   echo $key."<br />";

This returns:

Arizona ====================================================

Note that key() does not advance the pointer with each call. Rather, you use the next() function, whose sole purpose is to accomplish this task. This function is formally introduced later in this section.


mixed reset(array input_array)

The reset() function serves to set the input_array pointer back to the beginning of the array. This function is commonly used when you need to review or manipulate an array multiple times within a script, or when sorting has completed.


array each(array input_array)

The each() function returns the current key/value pair from the input_array, and advances the pointer one position. The returned array consists of four keys, with keys 0 and key containing the key name, and keys 1 and value containing the corresponding data. If the pointer is residing at the end of the array before executing each(), FALSE will be returned.

Array_Walk ()

boolean array_walk(array input_array, callback function [, mixed userdata])

The array_walk() function will pass each element of input_array to the user-defined function. This is useful when you need to perform a particular action based on each array element. Note that if you intend to actually modify the array key/value pairs, youíll need to pass each key/value to the function as a reference.

The user-defined function must take two parameters as input: the first represents the arrayís current value and the second the current key. If the optional userdata parameter is present in the call to array_walk(), then its value will be passed as a third parameter to the user-defined function.

You are probably scratching your head, wondering why this function could possibly be of any use (címon, you can admit it). Admittedly, I initially thought the same, until I did a bit of brainstorming. Perhaps one of the most effective examples involves the sanity-checking of user-supplied form data. Suppose the user was asked to provide six keywords that he thought best-described his state. That form source code might look like that shown in Listing 5-1.

Listing 5-1. Using an Array in a Form

<form action="submitdata.php" method="post">
   Provide up to six keywords that you believe best 
   describe the state in
   which you live:
   <p>Keyword 1:<br />
   <input type="text" name="keyword[]" size="20"
   maxlength="20" value="" /></p>
   <p>Keyword 2:<br />
   <input type="text" name="keyword[]" size="20"
   maxlength="20" value="" /></p>
   <p>Keyword 3:<br />
   <input type="text" name="keyword[]" size="20"
   maxlength="20" value="" /></p>
   <p>Keyword 4:<br />
   <input type="text" name="keyword[]" size="20"
   maxlength="20" value="" /></p>
   <p>Keyword 5:<br />
   <input type="text" name="keyword[]" size="20"
   maxlength="20" value="" /></p>
   <p>Keyword 6:<br />
   <input type="text" name="keyword[]" size="20"
   maxlength="20" value="" /></p>
   <p><input type="submit" value="Submit!"></p>

This form information is then sent to some script, referred to as submitdata.php in the form. This script should sanitize user data, then insert it into a database for later review. Using array_walk(), you can easily sanitize the keywords using a function stored in a form validation class:

>>> More PHP Articles          >>> More By Apress Publishing

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: