How to Use the Foreach Statement in PHP

By eHow Internet Editor

Rate: (0 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.

Instructions

Difficulty: Challenging

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

Step1
Create the array:
$arr = array(1, 2, 3, 4);
Step2
Write the condition:
foreach ($arr as $i => $value)
Step3
Write the action to be performed. In this case, the action is to multiply the initial value by 10: {
$arr[$i] = $value * 10;
}

Check the Statement

Step1
Check your code for syntax errors.
Step2
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.

Post a Comment

POST A COMMENT

Request a New How-To Article

Looking for more How To information? Chances are there’s an eHow member who knows how to do what you’re looking to do. Submit an article request now!

eHow Article: How to Use the Foreach Statement in PHP

eHow Internet Editor

eHow Internet Editor

Category: Internet

Articles: See my other articles

Related Ads

Internet

Veesites
Meet Virginia DeBolt eHow’s Internet Expert.