eHow launches Android app: Get the best of eHow on the go.

How To

How to Use the Foreach Statement in PHP

Contributor
By eHow Contributing Writer
(1 Ratings)

PHP has several conditional and loop statements that have been part of the language since its creation. Unlike them, the foreach statement was introduced in PHP later, influenced by other programming languages that used foreach for years. Unlike the other conditional and loop statements, the foreach statement is used only on arrays.

Difficulty: Challenging
Instructions

Things You'll Need:

  • PHP IDE or a text editor
  • Web server (preferably Apache)
  • MySQL database server, configured for work with PHP
  • PHP 5

    Use the Foreach Statement in PHP

  1. Step 1

    Create the array:
    $arr = array(1, 2, 3, 4);

  2. Step 2

    Write the condition:
    foreach ($arr as $i => $value)

  3. Step 3

    Write the action to be performed. In this case, the action is to multiply the initial value by 10: {
    $arr[$i] = $value * 10;
    }

  4. Check the Statement

  5. Step 1

    Check your code for syntax errors.

  6. Step 2

    Make sure your array has the following values: 10, 20, 30, 40.

Tips & Warnings
  • The foreach command has two correct syntaxes:foreach (array_expression as $value) and foreach (array_expression as $key => $value). Use the one you prefer.
  • Pay very careful attention to the syntax of the foreach statement.
Subscribe

Post a Comment

Post a Comment

Related Ads

  • Have you done this? Click here to let us know.
I Did This
Get Free Internet Newsletters

Copyright © 1999-2009 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy.   en-US Portions of this page are modifications based on work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License.

Demand Media
eHow_eHow Technology and Electronics