PHP $_POST Array Iteration?

Place for questions and answers for all newcomers and new coders. This is a free for all forum, no question is too stupid and to noob.
Post Reply
User avatar
Ryan
Posts: 13
Joined: Fri Jun 11, 2010 12:33 am

PHP $_POST Array Iteration?

Post by Ryan »

Hi guys,

I haven't been on these forums in a while, but I am back on now that school is out and everything! Okay, so basically I have some code that returns me an error when I checked it, but I don't know what I coded wrong. Here is the code for the erroneous function:

Code: Select all

        $items = array();
	$item_values = array();
	$item_index = 0;
		
	// Iterate through POST fields from form and add appropriate items
	// to the $items[] array
	function iterateArray($arr)
	{
		foreach ($arr as $key=>$value)
		{
			$arr[$key] = mysql_real_escape_string($value);
			if ((int)$value > 0) {
				$items[$item_index] = $key;
				$item_values[$item_index] = $value;
				$item_index++;
			}
		}
	}
Then, I passed in a $_POST array to iterate through (this is after the user has submitted the form):

Code: Select all

        iterateArray($_POST) or die('Failed to iterate $_POST fields');
Please help!
Ryan Chiu
Co-Founder, Part Owner, and President,
TradingSlots.com
(http://www.tradingslots.com)
Xaleph
Posts: 897
Joined: Mon Feb 07, 2011 2:55 am

Re: PHP $_POST Array Iteration?

Post by Xaleph »

Hi,

First of, you should check what values you are working with. $_POST can be empty, so it`s an empty array. You cannot loop trough it this way.
Second, your $items_ vars are declared outside of the function. This doesn`t work. You cannot use variables inside a function if they are not declared there. PHP has function scope. So the best way is to create the $items_ arrays inside the function. However, this triggers a new problem, because you can only return one variable. So I guess you should create an multi dimensional array to store the data in. IE. $items['value'], $items['key'] and $items['index'].

Obviously, that $items array should be created inside the function, and be returned after the loop is done. Also, if the parameter array is empty, or not an array at all, return false.

if(is_array($arr) and isset($arr[0]) ){
// continue doing whatever the function has to do
}else{
return false;
}
Post Reply

Return to “Beginner Help and Support”