The Most Useful Piece of PHP Code – Looping through Arrays

Working with and looping through arrays is one of the most useful things you can learn how to do with web applications. Anything from forms, API’s to configuration values, arrays make it easy in working with values. Take look at this simple example that illustrates the basics in working with the $_POST array.

$_POST['field1'] = 'value1';
$_POST['field2'] = 'value2';
$_POST['field3'] = 'value3';

foreach($_POST AS $key => $value)
	$$key = $value;

if($field1 == 'value1')
	echo '<p>$field1 has a value of "value1"!</p>';

if($field2 == 'value2')
	echo '<p>$field2 has a value of "value2"!</p>';
if($field3 == 'value3')
	echo '<p>$field3 has a value of "value3"!</p>';

foreach() loops are the best choice when working with arrays because you don’t have to worry about calling reset() on the array before going through the loop. Also, it is more simple than using the alternative version of the while loop: while (list($key, $value) = each($array)) .

With this in mind, you could loop through the $_POST array that is sent to a page when it comes from a form and make each key in the post array its’ own variable (similar to what is done in the sample above). You do this by creating a variable variable.

Using arrays and loops makes it simple to require certain elements in a form and also to populate a form with values they entered previously if there is an error. Take a look at the form example for a more in depth example in using arrays.

8 thoughts on “The Most Useful Piece of PHP Code – Looping through Arrays

    • Typically you would want to have an array of allowed form field keys that you want to accept to prevent malicious activity. This was mainly meant for illustration purposes.


      • Why not just:


        if($field1 == ‘value1’)
        echo ‘$field1 has a value of “value1”!’;


      • That will work, but sometimes over using extract() can introduce bugs that are difficult to track down (especially with loops inside of loops). Knowing how to work with arrays is valuable.

        I have worked at companies who do not allow the use of extract() because some consider it a lazy/messy way of coding.

        I personally like to use it with simple applications.


Comments are closed.