PHP
  Home arrow PHP arrow Page 4 - Arrays
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
VPS Hosting 
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Arrays
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 36
    2005-06-23

    Table of Contents:
  • Arrays
  • Outputting Arrays
  • Testing for an array
  • Locating Array Elements
  • Determining Array Size and Uniqueness
  • Other Useful Array Functions

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Arrays - Locating Array Elements


    (Page 4 of 6 )

    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.

    in_array()

    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!";

    Returning:

    =====================================================
    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_keys()

    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);
    print_r($keys);
    // Array ( [0] => Delaware [1] => Pennsylvania [2] => New Jersey )

    array_key_exists()

    boolean array_key_exists(mixed key, array target_array)

    key()

    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 />";
       next($capitals);
    }

    This returns:

    ====================================================
    Ohio
    Iowa
    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.

    reset()

    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.

    each()

    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">
      <p>
       Provide up to six keywords that you believe best 
       describe the state in
       which you live:
       </p>
       <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>
    </form>

    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


       · The writer forgot something important. Not only does array_pop return the last...
       · The capital of Nebraska, used in the example, is Lincoln (not Omaha).
     

    Buy this book now. This article is excerpted from the book Beginning PHP 5 and MySQL: From Novice to Professional, by W. Jason Gilmore (Apress, 2004; ISBN: 1893115518). Check it out at your favorite bookstore today. Buy this book now.

       

    PHP ARTICLES

    - Authentication Scripts for a User Management...
    - Utilizing the Use Keyword for Namespaces in ...
    - Building a User Management Application
    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT