• Announcements

    • boen_robot

      Guidelines and Netiquette   03/28/2017

      Posting Problems:   Having problems posting your topic? Read through this: To join, you agree to our terms and conditions and fill out and submit a registration form. An activation email will be sent to your email adress, so you'll need to verify your account. After that the account has to be validated by one of the moderators. This will mean that it can take up to a day to be activated. A couple of things to remember to ensure approval: Don't use an email address in one of those $2 four character .com domains eg. xyds.com. These will be deleted and the domain added to the banned list. Don't use an email address that is within a domain with a bad reputation for spam. A Google search is run on every email address and email domain. Don't sign up with an email address that doesn't exist, doesn't work or requires the sender to answer a quiz before their email can get to you. Put your country and or state and city in the signup form. Blank forms will go to the botton of the "to do" list. And make sure that your email address and your country match, saying you're from Alabama and using a .ru email address is not going to get you activated. After a membership is activated the first few posts will be monitored. Posting spam or unapproved topics described in the agreement results in an immediate ban. The email provider and the IP addresses associated with the account will be banned and all posts will be deleted. These strict measures have been deemed necessary to hinder spam. Sorry for any inconvenience this causes, but it's not liable to change. If, after reading this, you still can't post and don't understand why, contact one of the Moderators listed here.   Topic Guidelines   Including the following information can expedite an accurate response from board members: Must be a Specific Problem or Question related to web design and development Include Code in Question (wrap with   for small blocks of code and for longer blocks   ) Include Code Author Include Extra Notes/Modifications/Attempts Include web link to page/file when possible Content Guidelines   You may not post, upload, link to, or email any Content that contains, promotes, gives instruction about, or provides prohibited Content. Prohibited Content includes any Content that breaks any local, state, county, national or international law. Prohibited Content also includes: No direct or indirect advertising or websites, forums, products, services No hijacking of posts (do not post your question in someone elses) Content that infringes upon any rights [ex. MP3s and ROMs] (including, but not limited to, copyrights and trademarks) Abusive, threatening, defamatory, racist, or obscene Viruses or any other harmful computer software False Information or libel Spam, chain letters, or Pyramid schemes Gambling or Illicit drugs Terrorism Hacking or cheating for internet/online games Warez, Roms, CD-Keys, Cracks, Passwords, or Serial Numbers Pornography, nudity, or sexual material of any kind Excessive profanity Invasive of privacy or impersonation of any person/entity Hacking materials or information Posting Tips   There are more BBcodes than there are buttons for on the reply menu. To get the full list, click "BB Code Help" underneath the clickable smilie face menu. Use   for small snippets of code Use   for lengthy snippets of code Use   if your snippet is HTML (optional) Use   if your snippet is SQL (optional) Rules of Conduct   Be nice. There's no need for calling someone stupid if they ask an 'easy' question. Keep your avatars and signatures absolutely child friendly. We have a younger audience on this forum. Keep your language appropriate for the same reason above. Do not PM moderators for help on the forum. Post on the topic, or create a new one.   Spam:   Recently, as you have all without doubt noticed, we have had lots of spam and advertisement on the forum. Therefore, we'd like to alert you as to what to do when you have found any of the aforementioned annoying messages: it. Immediately. Give a clear reason, please, if the advertising is not evident. DO NOT POST! Report, let the post stay as is, and we will get to it, meanwhile if you continue to post as normal in the other threads, it won't be on the top so long. Refrain from PMing the member. This won't help at all, as they are most likely spambots anyway. Thank you.       Images in signatures:   After thinking of users on dial-up, we have decided to enforce the following rules regarding signatures. Please pay heed to them. Respecting these rules is respecting the members on this forum with dial-up. Signature rules: No animated images AT ALL. No matter the amount of animation. Maximum image widthxheight: 300x150 Maximum image (file) size: 15kb Use calm colors. Do not use highly contrasting images in your signature, as this can get really annoying when seeing several posts from one member in the same thread. The same prohibited content goes for images as for posts. Lastly, use common sense. No lengthy signatures please. Save us some scrolling. Thank you.       Links in signatures:   Please understand that w3schools.com only exists because of voluntary work and is barely supported by the advertising littered throughout the tutorials and the forum. So, please, stop advertising other sites. DO not post links that drive traffic away from the w3schools domain - especially to a site that offers similar if not identical information. Please help support the site by keeping individuals on it. Thank you. Here are some guidelines as to what you can put in your signature: w3schools links --> allowed w3.org links --> allowed browser links --> allowed html editor links --> allowed personal sites --> allowed tutorial sites competing with w3schools --> NOT allowed sites completely irrelevant to webprogramming and this forum --> NOT allowed   Thanks for understanding, and for taking the time to read this. ~W3Schools Modstaff~
Junitar

Why declaring empty variables at the beginning of a code?

14 posts in this topic

Hello,

 

I've just read the tutorial on how to process a form in PHP, available on this site, and I was wondering if there's a specific reason to declare empty variables (or arrays) at the beginning? I don't understand what is the point of doing so. For example, in the following code, why would the 2sd and 3rd lines be necessary?

<?php
$errors = [];
$name = $email = $message = '';

if (condition) {
	$errors['name'] = 'alert';
} else {
	$name = sanitize_input($_POST['name']);
	if (new_condition, $name) {
		$errors['name'] = 'new alert';
	}
}
	

 

Share this post


Link to post
Share on other sites

First of all, you should understand that a variable is little more than a name for content that can vary, and that this content comes in several prescribed forms called types.  An array is simply one of these variable types. In effect, a variable is simply a reference for changing content.  

A variable is like a storage room with an address.  It is a place where content is stored -- content that can be easily found, replaced, modified, or utilized when called upon.  When you initialize a variable, you declare the existence of a storage room and give it an address.  You can fill it at the moment you declare it, or you can leave it empty.  It is up to you.

By initializing all of your variables at the beginning of your routine they are ready to go.  What is more, they serve together as an outline of what your routine is about, because it is variables that contain your input and output.  After all, the whole purpose of a routine is to modify input in an effort to produce some desired output.

You might even want to organize your initialization strings in groups:  input variables, processing variables, and output variable.

Roddy

Share this post


Link to post
Share on other sites

You can't add something to a list if you haven't told the system that there's a list to be added to, so you have to declare $errors as an array before adding anything to it.

The reason $name, $email and $message are being initialized is so that when something tries to use them it's guaranteed that they will exist. You're not allowed to use a variable that doesn't exist, it doesn't make sense.

Take this example:

echo $a;

You're telling it to print the contents of variable $a, but you have not told it where $a is or what's in it, so the contents of $a is a mystery. It could print anything it wants and not be wrong, instead it chooses to throw a warning.

Share this post


Link to post
Share on other sites

Thank you to you both for your thorough feedbacks. I'm afraid it's still a bit fuzzy in my mind right now and the fact my English is limited sure doesn't help. I understand that a variable is used to store a content and it doesn't make sense to call a variable that doesn't exist. But in my example, I declared my variables later in the code:

…
$errors['name'] = 'alert';
…
$name = sanitize_input($_POST['name']);
…
$email = sanitize_input($_POST['email']);
…

this is why I don't completely understand the need of specifying at the beginning that $errors = [], $name = '', $email = '', etc.

If I write:

<?php
$test['letter1'] = 'a';
$test['letter2'] = 'b';

print_r($test);

// the output is Array ( [letter1] => a [letter2] => b )

my array is well declared and ready to be used without being initialized using $test = [].

 

I guess the answer to my question is somewhere in

3 hours ago, iwato said:

You can fill it at the moment you declare it, or you can leave it empty.  It is up to you.

and

2 hours ago, Ingolme said:

The reason $name, $email and $message are being initialized is so that when something tries to use them it's guaranteed that they will exist.

 

Share this post


Link to post
Share on other sites

If you had error messages turned on you would see  a lot of notices for undefined variables. PHP forgives many mistakes and tries to interpret what you do. If you forgot to declare the array but you're treating the variable as an array then it will implicitly create the array and throw a warning.

Put this at the very beginning of your code:

error_reporting(E_ALL);

Then it will show you when you've done something wrong.

If you're assigning a value before you use it, then you don't need to initialize it as an empty string, but take this example:

if($_POST['has_name'] == 1) {
  $name = $_POST['name'];
}

echo $name;

In this case, there's a chance that $name will not exist, so we would remedy that by setting $name to an empty string at the beginning:

// Initialize variable
$name = '';

// Give it a value under certain conditions
if($_POST['has_name'] == 1) {
  $name = $_POST['name'];
}

// Print the value
echo $name;

 

Share this post


Link to post
Share on other sites

Initializing variables can prevent a program from crashing unexpectedly. Isn't that a good enough reason?

Also Php is very, very forgiving (also known as "idiot-proof"). Why learn bad habits that are poor programming in other languages? Try your code in Javascript and you will see that it fails. In Javascript (and almost all languages) an array must be declared before use.

Share this post


Link to post
Share on other sites

Posted (edited)

Thank you very much Ingolme for your example, I understand it now!

28 minutes ago, davej said:

Initializing variables can prevent a program from crashing unexpectedly. Isn't that a good enough reason?

Also Php is very, very forgiving (also known as "idiot-proof"). Why learn bad habits that are poor programming in other languages? Try your code in Javascript and you will see that it fails. In Javascript (and almost all languages) an array must be declared before use.

Yes, I guess it's a good enough reason. Sorry if my question was dumb but I wanted to understand why it was a bad thing not to initialize variables first. I started learning PHP 2 days ago and I don't have enough experience in programming to know it could cause a program to crash. I got it now anyway, thanks.

Edited by Junitar

Share this post


Link to post
Share on other sites

Posted (edited)

2 hours ago, Junitar said:

 

Quote

Thank you to you both for your thorough feedbacks. 

You are welcome!

Quote

If I write:


$test['letter1'] = 'a';
$test['letter2'] = 'b';
Quote

my array is well declared and ready to be used without being initialized using $test = [].

You initialized the variable $test with the first statement -- namely,


$test['letter1'] = 'a';

1) You gave your storage room a name -- namely, $test.
2) You assigned to the room a certain kind of content -- namely, that of an array $test [...].
3) You placed content -- namely, 'a' -- in the first box of the array and named the box 'letter1'.

Because you performed items 1) and 2) PHP created an address for your room.  This is called initialization.
Because you gave the first box of your array a name, you have created a special kind of array called an associative array.
 

 

Edited by iwato

Share this post


Link to post
Share on other sites

Posted (edited)

Thanks for the clarification! Everything's clear.

Edited by Junitar

Share this post


Link to post
Share on other sites
4 hours ago, iwato said:

1) You gave your storage room a name -- namely, $test.
2) You assigned to the room a certain kind of content -- namely, that of an array $test [...].
3) You placed content -- namely, 'a' -- in the first box of the array and named the box 'letter1'.

 

This works in Php, but most programmers use various languages. For example in Javascript this same approach fails...

<script>

arrtest['letter1'] = 'a';
arrtest['letter2'] = 'b';

alert(arrtest['letter1']);

</script>

 

Share this post


Link to post
Share on other sites

Posted (edited)

Dave, I have not tried it and will take your word for it.

Important for Junitar is that he understands the notion of initialization.

For example, in the following code
 

var myvar = [];
function doSomething(input1, input2) {
  var myVar = [input1, input2];
  alert (myVar[0]);
}
doSomething('a', 'b');

the statement

var myVar = [];

initializes the variable myVar by providing a name and variable type.  Javascript provides the address.

The same is true for PHP; simply the syntax is different.  I cannot speak on behalf of other languages, but is it not likely that all object-oriented languages operate on a similar principle?

 

Edited by iwato

Share this post


Link to post
Share on other sites

In your code, you have two different variables that both happen to have the same name, one of them is given a value while the other one is left empty. That's not a very good example.

Share this post


Link to post
Share on other sites

var myVar = []; (forgetting the typo) is global, while the one within function again using var its scope is now restricted to that function and therefore unrelated to the global variable declared outside the function.

Share this post


Link to post
Share on other sites

Posted (edited)

Dsonesuk:  That was not a typo.  I placed the blank purposefully so that the brackets are easier to read.  I do understand how someone could misunderstand, however.  Next time I will make a note of the insertion so that there is no confusion.

Ingolme:  You are correct.  The notion of scope did come across my mind as I was writing the code, but the code worked, so I ignored any further discussion.  Besides, it looked nice .... :-)

Janitor:  There are two different variables with the same name, but there are also two different addresses:  one outside of the function, and one inside the function.  If you Google for the city of Paris, you will discover one in Kentucky, USA and one in France.  Who knows?  There are probably more.  In any case, each has its own address.  

This said, each variable is initialized:  one with no content outside the function, and one with content inside the function.  

The principle is the same as I what I wrote in my previous entry:  pprovide a name and variable type (the kind of content that you can store in the room), and Javascript assigns an address.  This is initialization!

Edited by iwato

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now