Jump to content

Initial Array with loop


doubledee

Recommended Posts

I am trying to initialize every value in my $errors array to have a value of '' so I don't get "undefined variable" errors!

 

Here is what I have...

 

//Put in some values and then try to erase them.
$errors = array('firstName' => 'Enter First Name', 'lastName' => 'Enter Last Name');

//Want an initialized array.
foreach($errors as $key => $value){
$key = '';
}

 

But that doesn't seem to work when I run

 

print_r($errors, true);

 

Thanks,

 

 

Debbie

 

 

Link to comment
Share on other sites

What are you trying to do, actually? Maybe you could broaden the explanation a bit, and we can help you come up with a solution.

 

Sorry, thought I did.

 

I *always* see to have issues with getting those nasty "variable undefined" errors that PHP spits out.

 

In particular, I was getting them on my $errors array.

 

Here is my code...

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
	<title></title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<link type="text/css" rel="stylesheet" href=".css">
	<style type="text/css" >
		form{
			width: 500px;
			margin: 0 auto;
		}
	</style>
</head>
<body>
	<?php
		// Initialize.
/*
		$errors = array();
		$errors['firstName'] = '';
		$errors['lastName'] = '';
		$firstName = $lastName = '';
*/
		$errors = array('firstName' => 'Enter First Name', 'lastName' => 'Enter Last Name');

		foreach($errors as $key => $value){
			$value = '';
			echo "The value at $key is $value.<br />";
//				echo "The value at $key is $value.<br />";
		}


		echo "print_r = " . print_r($errors, true);
		exit();

		if (isset($_POST['submit'])){
			// Handle Form.

			// Trim all incoming data.
			$trimmed = array_map('trim', $_POST);

			// Check First Name.
			if (preg_match('/^[A-Z\'.-]{2,20}$/i', $_POST['firstName'])){
				$firstName = $_POST['firstName'];
			}else{
				$errors['firstName'] = 'Please enter your First Name.';
			}

			// Check Last Name.
			if (preg_match('/^[A-Z\'.-]{2,20}$/i', $_POST['lastName'])){
				$lastName = $_POST['lastName'];
			}else{
				$errors['lastName'] = 'Please enter your Last Name.';
			}

			// if there are errors then go back to the form and display them
		}else{

		}
	?>
	<form action="" method="post">
		<fieldset>
			<legend>Billing Details</legend>
			<ol>
				<li>
					<label for="firstName">First Name:</label>
					<input id="firstName" name="firstName" class="text" type="text" />
					<?php echo $errors['firstName']; ?>
				</li>
				<li>
					<label for="lastName">Last Name:</label>
					<input id="lastName" name="lastName" class="text" type="text" />
					<?php echo $errors['lastName']; ?>
				</li>
			</ol>
			<input type="submit" name="submit" value="Process Order" />
			<input type="hidden" name="submitted" value="true" />
		</fieldset>
	</form>
</body>
</html>

 

 

if I didn't add this code, then I got those errors..

 

/*
		$errors = array();
		$errors['firstName'] = '';
		$errors['lastName'] = '';
		$firstName = $lastName = '';
*/

 

The problem is that I don't want to have to mimic that for 30-40 fields in my form?!  :o

 

So I thought if maybe I could write a loop and assign every element a '' value it ould shut up PHP.

 

Does that make more sense?

 

 

 

Debbie

 

 

Link to comment
Share on other sites

Try this.

foreach($errors as $key => $value){
$errors[$key] = '';
}

 

When I tried this code I got this...

 

The value at firstName is Enter First Name.

The value at lastName is Enter Last Name.

print_r = Array ( [firstName] => [lastName] => )

 

Which means it isn't working.

 

 

 

Debbie

 

Link to comment
Share on other sites

You don't need to initialize every index. Just check to see if each index is not empty before you try to echo it.

 

<label for="lastName">Last Name:</label>
<input id="lastName" name="lastName" class="text" type="text" />
<?php echo !empty($errors['lastName']) ? $errors['lastName'] : ''; ?>

Link to comment
Share on other sites

You don't need to initialize every index. Just check to see if each index is not empty before you try to echo it.

 

<label for="lastName">Last Name:</label>
<input id="lastName" name="lastName" class="text" type="text" />
<?php echo !empty($errors['lastName']) ? $errors['lastName'] : ''; ?>

 

Okay, that worked, but can you please explain the method to the madness of this?!

 

I don't understand why these errors occur.

 

For instance, if I comment out this line...

 

//			$firstName = $lastName = '';

 

I run into similar issues...

 

 

Debbie

 

Link to comment
Share on other sites

Attempting to access a variable or array element before it's been initialized will throw a warning. Checking to see if it exists before attempting to access it prevents the warning by not accessing it if it hasn't been initialized.

Link to comment
Share on other sites

Attempting to access a variable or array element before it's been initialized will throw a warning. Checking to see if it exists before attempting to access it prevents the warning by not accessing it if it hasn't been initialized.

 

And there is no way around that?

 

If so, then isn't it better to just define every variable you will ever use before you start using them to avoid this issue?

 

Thanks,

 

 

Debbie

 

Link to comment
Share on other sites

By the way, I added some styling to the code you gave me...

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
	<title></title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<link type="text/css" rel="stylesheet" href=".css">
	<style type="text/css" >
		form{
			width: 600px;
			margin: 0 auto;
		}

		.error{
			font-weight: 100;
			color: #F00;
		}
	</style>
</head>
<body>
	<?php
		// Initialize.
		$firstName = $lastName = '';
		$errors = array();

		if (isset($_POST['submit'])){
			// Handle Form.

			// Trim all incoming data.
			$trimmed = array_map('trim', $_POST);

			// Validate First Name.
			if (preg_match('/^[A-Z\'.-]{2,20}$/i', $_POST['firstName'])){
				$firstName = $_POST['firstName'];
			}else{
				$errors['firstName'] = 'Please enter a valid First Name.';
			}

			// Validate Last Name.
			if (preg_match('/^[A-Z\'.-]{2,20}$/i', $_POST['lastName'])){
				$lastName = $_POST['lastName'];
			}else{
				$errors['lastName'] = 'Please enter a valid Last Name.';
			}

			// if there are errors then go back to the form and display them
		}else{

		}
	?>
	<form action="" method="post">
		<fieldset>
			<legend>Billing Details</legend>
			<ol>
				<li>
					<label for="firstName">First Name:</label>
					<input id="firstName" name="firstName" class="text" type="text"
								 value="<?php echo $firstName; ?>" />
					<?php
						if (empty($errors['firstName'])){
							echo '';
						}else{
							echo '<span class="error">' . $errors['firstName'] . '</span>';
						}
					?>
				</li>
				<li>
					<label for="lastName">Last Name:</label>
					<input id="lastName" name="lastName" class="text" type="text"
								 value="<?php echo $lastName; ?>" />
					<?php
						if (empty($errors['lastName'])){
							echo '';
						}else{
							echo '<span class="error">' . $errors['lastName'] . '</span>';
						}
					?>
				</li>
			</ol>
			<input type="submit" name="submit" value="Process Order" />
			<input type="hidden" name="submitted" value="true" />
		</fieldset>
	</form>
</body>
</html>

 

Looks pretty fancy, eh?!  :D

 

 

Debbie

 

 

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.