Jump to content

Resolve array error w/out error suppression operatior @


OldWest

Recommended Posts

My script IS working, but I can't get around a blank array error when no errors exist.

 

Below is my code, and as you can see, I am being handed this:

Notice: Undefined variable: error in C:\wamp\www\php\form_validation.php on line 19 as a result of my ... if (is_array($error)) { ... .. I could do if (@is_array($error)) { (note the @), but I hate using that thing... I've tried several things with no luck, so any ideas welcome at this point.

 

<?php
  if (isset($_POST['set_test'])) {
      if (!preg_match("/^[A-Za-z' -]{1,50}$/", $_POST['first_name'])) {
          $error[] = "Please enter a valid First Name";
      }
      if (!preg_match("/^[A-Za-z' -]{1,50}$/", $_POST['last_name'])) {
          $error[] = "Please enter a valid Last Name";
      }
      if (is_array($error)) {
          foreach ($error as $err_message) {
              echo $err_message . "<br />";
          }
      }
  }
?>

Link to comment
Share on other sites

You can also use if(!empty($error)) (for those of us who would define the array at the start of the code.)

 

Not implying you shouldn't initialize your variables, but the empty() method checks if the variable is set I think.

Link to comment
Share on other sites

See new comments within the code . . .

 

<?php
if (isset($_POST['set_test'])) {
$error = array();  // initialize an empty array
if (!preg_match("/^[A-Za-z' -]{1,50}$/", $_POST['first_name'])) {
	$error[] = "Please enter a valid First Name";
}
if (!preg_match("/^[A-Za-z' -]{1,50}$/", $_POST['last_name'])) {
	$error[] = "Please enter a valid Last Name";
}
if (!empty($error)) {  // if array is not empty, implode to a <br> separated string and echo (eliminates foreach loop's trailing <br>).
	echo implode( '<br>', $error);
}
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.