As I'm going through tutorials I keep getting stuck when it comes to Variables (among other things but that is the first thing I get stuck on). I can't seem to grasp what a variable actually is or what it's function is. None of the tutorials really say. At least not in terms I can understand. One discribes varibles as something that holds data, like a coin purse holds coins. I can visualize that however, I can't grasp the purpose of a variable or in which cases you would use varibles.

Can anyone explain Variables to me in laman's terms? Keep in mind that math was my absolutely worst subject so explain like you would someone that is completely clueless (that would be me LOL!).

Thank you.

    The best way to think of vriables as storage space for inforation - thats all they are, named memory locations in which data is stored 🙂

    For example this stores a string in the memory location called "String"

    <?php
      $String = 'This is an example of a string stored in a variable.';
    ?>
    

    Cheers,

    Ryan Jones

      I will tell you first why you want to use variable and then you will understand what is a variable.

      Lets suppose I have a database where I keep my registered user's name.

      In php I will have a script to insert the name in the db, something like this.

      INSERT INTO mymembers (firstname) VALUES ('John');

      Now everytime I run the script I have an entry with the firstname John, unfortunately my members are not all John, so I need a way to vary the names, you got it variables.

      How do I do that?

      Well, with php it's very easy, first my members will register with a form on a website, in the form I have a field like that.

      First Name: <input type="text" name="fname" size="20">

      This will give you the typical form field that you see usually.

      What is interesting though is the name "fname" will now be use by the php engine as a variable, which mean whatever you will write down in the box, will be retain in the variable named "fname".

      So to get back to my example of the insert in the db now I will have this;

      INSERT INTO mymembers (firstname) VALUES ('$fname');

      The dollar sign tell php this is a variable.

      So if you typed in the box Robert then it would be the same as if I had wrote the insert manually as

      INSERT INTO mymembers (firstname) VALUES ('Robert');

      And the next user will write something different but for my script it doesn't matters because I'm using a variable.

      Hope this help.

      Gamebits

        @:

        I have some BIG issues with your code there.

        1) Not everyone has register globals turned on so it would be $_POST['fname'] not $fname.
        2) You gave an example of putting pn parsed content from the user strait intoaDB, a VERY bd idea to say the least.

        Just a few notes.

        Ryan Jones

          Thank you Ryan and Gamebits!

          I'm not at the stage yet where I can write a script. But hope to be eventually. This is all so foreign to me 😕

          Gamebits...how you explained it with the example of the name form was exactly what I needed to get some understanding of how variables work. I would imagine there are many ways to use variables in situations where you need to collect data from users right? Would you that is their main function? To collect outside data like that? Or do they have other uses as well?

          Thanks.

            Variables are always used as a means to get different kinds of data to whatever part of your script.

            For example: usage in getting the forms gamebits explained is one but not the only way of using them...
            You can set a variable to 0 and increment it by 1 whenever your loop executes and when it reaches certain value the loop ends. Like in example:

            $i=0;
            while($i<10){
                 //do something
                 $i++;
            }
            

            This loop will repeat itself 10 times because first value of variable $i is 0 (we set that before the loop) and every next time the value is greater than previous value by one i.e. in this case they will be 1, 2, 3, 4, 5, 6, 7, 8, and 9 and that is just because 9 is smaller than 10 (I figure you know this much math but figured to explain it anyway he he he)...

            Also you can use variables in functions like in this example:

            function something($var){//first define a function
                 $var = ($var/2) + ($var*31);
                 return $var;
            }
            echo something(23);//use a function
            //this will output 724.5
            

            This example shows you one other function of variables: they are used to define what will happen with the input of the data that comes through function... In this example I used something weird so don't concern yourself with that but visualise the usage of the variable - it becomes whatever we pass to the function - in this example it will be 23.

            These examples are only few of the possibilities of using variables in your script...

            You will see when you start coding that you will use variables for all sorts of things...

              I guess it's been touched upon here, but I want to point it out specifically:

              Variables in PHP can hold any type of data. Strings, numbers (integers, floating-points, hexadecimal, binary, etc. etc.), references (such as to other variables, file streams, etc.), resources, arrays (sort of like a collection of variables), etc. etc.

              If you've coded in languages such as C++, you'll find that PHP is very forgiving in typecasting and whatnot. Basically, if you use this code:

              $variable = 123;

              $variable is technically an integer type variable, but if you pass it along to an [man]echo/man statement, PHP uses the equivalent string automatically ("123") since it expected a string.

              Another thing - PHP.net has an awesome online manual. If you start coming across functions/structure/etc. you want to know more about, there are detailed (with few exceptions) manual entries for them online. Simply go to www.php.net and search for it.

              EDIT: I should also point out that the function posted above will not output what was expected - it [man]return[/man]ed something, it didn't output it. It should have been written using [man]echo[/man] or [man]print[/man] instead of return.

                @

                The example was intended to explain was is a variable not a dicertation of proper syntax in programing, when somebody is at the begining and want to know what is a variable I don't think it is appropriate to bury him under a ton of rules.

                And yes I know about register global as well as I know that you never trust user input in a form, why do you think we have addslashes, stripslashes, htmlspecialchars, etc.etc.etc.

                One step at a time.

                Gamebits

                  gamebits wrote:

                  One step at a time.

                  Very true, I couldn't agree more. But still, shouldn't we at least start them off on the right foot? Or, if we throw a bunch of technicalities at them, at least let it be for the sake of future clarification.

                  One of the biggest pet peeves I have is the world of education, especially in mathmatics. As you progress up the scale, from grade school to college, the next teacher always has a better, easier, quicker, more acceptable, more thorough way of doing something. Ask an 8th grader what the square root of -4 is and he'll tell you with all the confidence in the world that it can't be done. Ask a high schooler, and he'll immediately tell you 2i.

                  Hehe, sorry for my mini-rant there. Carry on. [/soapbox] :p

                    But still, shouldn't we at least start them off on the right foot?

                    I agree, since in this case trying to code with $fname may not work on a given new PHP installation, and it is possible to pass of $_POST['fname'] as just another variable without a full introduction into arrays.

                    As you progress up the scale, from grade school to college, the next teacher always has a better, easier, quicker, more acceptable, more thorough way of doing something. Ask an 8th grader what the square root of -4 is and he'll tell you with all the confidence in the world that it can't be done. Ask a high schooler, and he'll immediately tell you 2i.

                    hmm... but it is true that the square root of -4 cant be found, so long as we are working with real numbers alone. The teacher who says that still is starting the students off on the right foot, just without a full explanation that it is solely within the context of the set of real numbers.

                      Did you ever play piano?

                      You don't start to learn by playing beethoven fifth symphony.

                      Look at the question, "what is a variable and why should I use them".

                      You learned to walk before you learned to run.

                      Gamebits

                        "You learned to walk before you learned to run."

                        Very true. In my case I'm still learning how to crawl 😃

                        Thank you all for the explanations. I think I'm starting to slowly understand variables. At least I understand what they are used for in a general sense. I think what is going to be tough for me is my lack of math skills.

                        "This loop will repeat itself 10 times because first value of variable $i is 0 (we set that before the loop) and every next time the value is greater than previous value by one i.e. in this case they will be 1, 2, 3, 4, 5, 6, 7, 8, and 9 and that is just because 9 is smaller than 10 (I figure you know this much math but figured to explain it anyway he he he)..."

                        Yes, I understood that and even the code: ($i<10) made sense to me since you explained it. I know that < means less than. I did learn that in math.

                        Does the $i=0, does the i stand for increments?

                        "This loop will repeat itself 10 times because first value of variable $i is 0"

                        If your setting a loop to repeat itself 10 times, why do we use 0 instead of the number 10? $1=0, at first glance common sense would say ok, that means zero times. $1=10 would mean ten times. But I know there's a method in PHP, so I'm just trying to understand why 0 would mean 10. Or am I way off the map at this point and missed the whole meaning here?? Wouldn't be the first time 😃

                          Does the $i=0, does the i stand for increments?

                          It is a legacy from FORTRAN, I believe. It is just a variable to control loop iteration, you could use any other name, e.g. a $count would do just as well.

                          If your setting a loop to repeat itself 10 times, why do we use 0 instead of the number 10? $1=0, at first glance common sense would say ok, that means zero times. $1=10 would mean ten times. But I know there's a method in PHP, so I'm just trying to understand why 0 would mean 10.

                          Well, more completely: the loop will repeat itself 10 times because the first value of $i is 0, and the last is 10, upon which the loop terminates before its body can be executed (i.e. the last $i < 10 comparison terminates the loop, since it becomes 10 < 10, which evaluates to false).

                            jkphp wrote:

                            Does the $i=0, does the i stand for increments?

                            $i is as laserlight pointed out just a variable that can be used in a loop. As i said just visualise on how it is used i.e. I set variable $i (which I will use in a loop later on) to 0 just for my convenience.
                            I could assign a value 10 but the loop will never start if a comparison is left like it is right now ($i<10) because it will fail.
                            I used $i to be 0 and then used comparison $i<0 as a loop terminator only so it can be clear to me or all others reading my code that the loop will execute 10 times...
                            I could have used $i=10; and then set to loop through a while loop untill it reaches 20 by setting a comparison to $i<20... Basically it would do the same thing - it would execute 10 times...

                            So basically to understand the lopp issue: before you start using while loop like I did you set a loop index (I believe it is the short of that) as I did ($i=0; ) and later on you start a while loop by setting two important things in it: comparison which will be checked on start of every pass of the loop ($i<10) and index modifier to change the value of a loop index untill it reaches it end to break out of the loop (in my case I used an increment operator to increment a value of the variable by 1 on each run i.e. $i++; )...

                              Write a Reply...