Page 1 of 1

PHP $_POST Array Iteration?

Posted: Tue Jun 07, 2011 11:36 am
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!

Re: PHP $_POST Array Iteration?

Posted: Tue Jun 07, 2011 1:07 pm
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;
}