Page 1 of 1

Wierd invalid foreach error

Posted: Tue Jul 17, 2007 9:12 am
by mattcooper
Hi guys,

The following code is a method in a class that will be performing form validation:

Code: Select all

function validateForm()
	    {
	        // @function   validateForm
	        // @access     public
	        // @purpose    returns a list of things to fix
	        // @return     boolean (array on false)
	        
	        // instantiate the validator class
	        $v = new Validator();
            
	        echo '<pre>';
	        print_r($this->validationArray);
	        echo '</pre>';
            
            if(empty($this->validationArray)) {
               
                echo 'Array empty';
            }
	        foreach ($this->validationArray as $value => $dataType) {
	            
	            // concatenate 'validate' and $dataType to construct method call
	            $method = 'validate'. $dataType;
	            // validate the submitted data
	            $v->$method($value);
	        }
	        if ($v->errors) {
	            
	            $this->errorHandler($v->errors);
	            return false;
	        } else {
	            
	            // do whatever has been specified
	        }
	        return true;
	    }
Unfortunately, when I run it I get the following error:

Code: Select all

Warning: Invalid argument supplied for foreach() in /sandbox/k/keytravel/trunk/codebase/htdocs/testing/classes/Form_handler.php on line 77
If you run the code yourself you'll see that print_r confirms that there is an array, but that empty() returns true as well. Also, if I echo out either $value or $dataType in the loop, both are present. Incidentally, this class is called "Form_handler" so don't be confused by the new Validator instance...

So why is PHP telling me my foreach is invalid? Usually this is the easiest thing of all to debug, bt I'm a bit confused by this one.

All help greatly appreciated as always ;)

Posted: Tue Jul 17, 2007 9:18 am
by volka
please try

Code: Select all

isset($this->validationArray) or die('thre is no $this->validationArray');
echo 'type: ', gettype($this->validationArray), "<br />\n";
foreach ($this->validationArray as $value => $dataType) {

Posted: Tue Jul 17, 2007 9:31 am
by mattcooper
Thanks Volka... I was too late to edit my post and tell everyone that I'd found the bug elsewhere - there was a call to that method in the constructor for the class and I was also invoking that method in my script... caused a bit of confusion, that one!

Thank you for your help, I have kept the snippet becuase it will be useful for debugging other things.

Cheers!