PHP Variables and Constants

After learning the PHP Keywords In this post, we learn about the PHP Variables and Constants, and also you will learn how to learn to store information in a variable and use constants for storing fixed values in PHP.

PHP Variables and Constants

PHP Variables


Variables are used to store the data, string, text, and numbers. Variable values can change over the course of a script. Here’re some important things to know about variables:

  • In PHP, a variable can not need to be declared before adding a value. PHP automatically converts the variable to the correct data type, depending on its value.
  • After declaring a variable it can be reused throughout the code.
  • The assignment operator (=) used to assign the value to a variable.

Variable comes to the rescue, A variable is name given to memory location which is used to store particular value. These values may be fixed or it can be dynamic.

In PHP variable can be declared as: $var_name = value;

A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).

PHP Variables and Constants

Naming Conventions for PHP Variables


These are the following rules for naming a PHP variable:

  • It starts with the $ sign, followed by the name of the variable
  • Name must start with a letter or the underscore character
  • Name cannot start with a number
  • It can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive ($age and $AGE are two different variables)
Remember that PHP variable names are case-sensitive.
# Example:
<?php 
// Declaring variables
 $txt = "Hello World!";
 $number = 10; 
// Displaying variables value
 echo $txt; 
// Output:
 Hello World! 
echo $number; 
// Output: 
10 
?>

In the above example, we have created two variables where the first one has assigned with a string value and the second has assigned a number. Later we’ve displayed the variables values in the browser using the statement. echo The PHP echo statement is often used to output data to the browser. We will learn more about this in the upcoming chapter.

Variable Types


The variables can be declared anywhere in your PHP program. Based on the declaration of your variable scope is decided for each variable. Scope of a variable means the part of program where variable can be accessed.

Based on scope there are three types of variables.

  1. Local variable
  2. Global variable
  3. Static variable

1. Local Variable

A variable which is declared within any function is known as local variable , it has local scope meaning it cannot be accessed outside the function.

#For Example:

<?php
       function localVariable()
      {
          $a = 6;
          echo $a;
      }
      localVariable();
       echo $a;  
   // Output
      6    
?>

Here in this example $a is declared inside function localVariable() so it can not be accessed outside the function body, so if we try to uncomment the code in our program it will not print the value of $a as its accessed outside the block.

2. Global Variable

A variable declared outside any function has global scope so it can be accessed from anywhere in the program.

#For Example:

<?php
       $a = 6; 
      // global variable
       function globalVariable()
       {
         echo $a;
       }
       globalVariable();
       echo $a;  
      // Output
        6           
?>

Here in this example $a is declared outside the function so it has global scope and it can be accessed inside function as well as anywhere outside in the program.

3. Static Variable

The variable declared with keyword static is known as static variable , it has local scope meaning it can not be accessed outside the function , the benefit of static variable is it retains its value between function calls.

#For Example:

<?php
       function staticVariable()
       {
          static $a = 6;
          echo $a;
          $a++;
       }
       staticVariable();
       staticVariable();
       staticVariable();
?>

For this example the value of $a will be initialized only once for all function calls and the value will be retained between function calls so the output will be 10 for first call , 11 for second call and 12 for the third call.

PHP Constants


Constant is a name or an identifier for a fixed value. Constant are like variables except for that one they are defined so they can not be undefined or changed.

PHP Variables and Constants

A constant is an identifier (name) for a simple value. Value not changed during the script.

A valid constant name starts with a letter or underscore (no $ sign before the constant name).

Constants are very useful for storing data that doesn’t change while the script is running. Common examples of such data include configuration settings such as database username and password, website’s base URL, company name, etc.

Constants are defined using PHP’s define() function, which accepts two arguments: the name of the constant, and its value. Defined the constant value the we can be accessed at any time just by referring to its name. Here is a simple example.

Create a PHP Constant


To create a constant, use the define() function.

   define(name, value, case-in-sensitive)

Parameters:

  1. name: Specifies the Name of the constant
  2. value: Specifies the Value of the constant
  3. case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false
# Example:
<?php 
    define("GREETING", "Welcome to programmingpot.com !"); 
    echo GREETING; 
   // Output
    Welcome to programmingpot.com !
?>

Naming Conventions for PHP Constants


Name of constants must follow the same rules as variable names, which means a valid constant name must starts with a letter or underscore, followed by any number of letters, numbers or underscores with one exception: the $ prefix is not required for constant names.

So this way, we can use the PHP Variables and Constants in our PHP programming. The PHP Variables and Constants are very important for the core PHP programming. So the PHP Variables and Constants is very important.


Also Read:

PHP Switch Case Statement

PHP Control Structures

70 thoughts on “PHP Variables and Constants”

  1. Magnificent goods from you, man. I have take note
    your stuff previous to and you’re simply too fantastic.
    I really like what you’ve acquired right here, certainly like what you are stating and the best way during
    which you say it. You’re making it enjoyable and you
    still care for to stay it sensible. I cant wait
    to learn far more from you. This is really a
    tremendous web site.

    1. ProgrammingPot says:

      Thank You so much @kostenlose for your great words. Keep Staying with us and supporting us. I will write the Qualityful and enjoyable post for all.

  2. road sign suppliers UK says:

    I like this post, enjoyed this one regards for posting.

    1. ProgrammingPot says:

      Thank You @road sing suppliers UK and Keep Staying With Us.

  3. I am regular visitor, how are you everybody?
    This article posted at this website is in fact pleasant.

    1. ProgrammingPot says:

      Thank You @Solarwinds Server Monitoring for your Great Words. And Keep Staying with Us.

  4. Greetings, There’s no doubt that your blog could be having web browser compatibility issues.
    Whenever I look at your site in Safari, it looks fine however when opening in I.E., it has some
    overlapping issues. I simply wanted to give you
    a quick heads up! Other than that, wonderful blog!

    1. ProgrammingPot says:

      Thank You @corrugated roofing London for your Great Advice and Feedback. We will fix this Problem as soon as Possible.

  5. Hi there to all, how is the whole thing, I think every one is getting more from this website, and your views are nice in favor of new people.

    1. ProgrammingPot says:

      Yes, Everything is good @money lender Singapore and Thank you so much.

  6. money lender says:

    Hurrah! In the end I got a blog from where I be capable of really obtain valuable facts regarding my study and knowledge.

    1. ProgrammingPot says:

      Thank You for your Great words! @money lender. Keep Staying with us.

  7. After looking over a handful of the blog articles on your web page, I honestly appreciate
    your way of blogging. I added it to my bookmark website list and will be
    checking back soon. Take a look at my website too and let me know what you
    think.

    1. ProgrammingPot says:

      Thank you, dear. And Your website is wonderful man its very beautiful UI design. Keep Staying With Us.

  8. Thhe other day, while I was at work, my sister stole mmy iPad and tested to ssee if it
    can survive a thirty foot drop, just soo she can be a youtube sensation. My iPad is now
    broken and she has 83 views. I know this
    is entirely offf topic but I had to share it with
    someone!

    1. ProgrammingPot says:

      Thank you for sharing your topic @Creative Wedding Photographer London. And keep Staying With Us.

  9. cardapio says:

    Apaixonada por Alimentação Saudável e Saúde
    do Corpo.

  10. A principal causa da ejaculação precoce é a ansiedade.

  11. Monte a sua dieta para ganhar massa muscular.

  12. É um grande aliado para ganhar massa muscular.

  13. Este é um treino para ganhar massa muscular no peito.

  14. If you want to obtain a goood deal from this post then you have to apply these methods to your
    won weblog.

    1. ProgrammingPot says:

      Yes, Exactly.

  15. A principal causa da ejaculação precoce é
    a ansiedade.

  16. www says:

    you are actually a good webmaster. The web site loading speed is incredible.
    It sort of feels that you are doing any unique trick.
    Furthermore, The contents are masterwork. you’ve performed a fantastic activity in this subject!

    1. ProgrammingPot says:

      Thank You for your good word. Actually, I using my own WordPress theme and not any more plugins on my website, which makes my website loading speed is very fast. And keep staying with us.

  17. It is perfect time to make some plans for the future and it’s time
    to be happy. I’ve read this post and if I could I want to suggest you some interesting things or suggestions.

    Perhaps you could write next articles referring to this article.
    I wish to read more things about it!

    1. ProgrammingPot says:

      Thank You so much @channel helicopter for your great Suggestion. I definitely refer this article link to other articles. Keep staying with us.

  18. I am extremely impressed with your writing abilities
    as neatly as with the structure to your weblog. Is this a paid subject matter or did
    you customize it your self? Either way stay up the excellent quality writing, it is uncommon to peer a great blog like this one these days..

    1. ProgrammingPot says:

      Thank You so much for your positive comment. this is not any paid subject matter I’m just using my own WordPress theme and customize in my own way. And the subject material is all original which I wrote here. Keep staying with us.

  19. gura says:

    thanks for this great article. this really useful for new bloggers. keep it

    1. ProgrammingPot says:

      Thank You for your Great word. Keep Staying With Us.

  20. Em alguns casos, pode tratar-se de um problema sério.

    1. ProgrammingPot says:

      Sim. Mantenha-se com a gente.

  21. Em poucos dias você estará livre das verrugas.

  22. Marylyn says:

    Fortunately is that the clinical community is actively investigating Garcinia cambogia extract cambogia.

  23. Amelie says:

    I’ve been taking 2 each day, 1 60 minutes prior to lunch and 1 in the late mid-day
    before supper and have actually shed a great deal of weight started taking it I was watching TELEVISION
    as well as I saw just how a medical professional was supporteding this item so I said why not and
    also it functioned!

  24. Wilhelmina says:

    The substance has actually been discovered via
    comprehensive research which was carried out on pure garcinia cambogia extract to have a far better understanding and also research study of the material that has actually confirmed to have actually opened new frontiers in the area
    of clinical science that can aid people in minimizing
    their weight in a totally natural as well as reliable fashion without undertaking much inconvenience.

  25. Amber says:

    insert your data

    1. ProgrammingPot says:

      There is already inserted.

  26. Ⲛeat bⅼog! Is your tһeme custom made or ɗid
    you download it from somewhere? A theme like yours
    with a few simple aԁjustements would realⅼy
    make my blog shine. Please let me know wheгe you
    got yoᥙr design. Bleѕs you

    1. ProgrammingPot says:

      This is my own custom design if you want then please contact me.

  27. I have fun with, cause I found just what I was having a look for.
    You’ve ended my 4 day long hunt! God Bless you man. Have a great day.
    Bye

    1. ProgrammingPot says:

      Thank you so much man for your great word. keep staying with us. tack care

  28. metodo novo says:

    Para ganhar massa muscular, a dica é alternar.

    1. ProgrammingPot says:

      Thank You, Man.

  29. Would love to perpetually get updated great web site!

    1. ProgrammingPot says:

      Thank You so much, Man. Keep staying with us.

  30. My brother suggested I might like this web site.
    He used to bee entirely right. This post truly made my day.
    You cann’t imagine simply how a lot time I had spent ffor this information! Thank you!

    1. ProgrammingPot says:

      Thank you so much dear! Keep Staying with us.

  31. Pingback: Google
    1. ProgrammingPot says:

      Thank You so Much, Dear!

  32. Definitely believe that which you stated. Your favorite justification seemed to be on the internet the easiest thing to be
    aware of. I say to you, I certainly get irked while people consider worries that they
    just don’t know about. You managed to hit the
    nail upon the top as well as defined out the whole thing without having side-effects , people
    can take a signal. Will probably be back to get more.
    Thanks

    1. ProgrammingPot says:

      Thanks .

  33. Hello there, just became aware of your blog through Google, and found that it
    is truly informative. I’m gonna watch out for brussels. I’ll be grateful
    if you continue this in future. Lots of people will be benefited
    from your writing. Cheers!

    1. ProgrammingPot says:

      Thank You so much. Keep Staying With Us.

  34. I am not real good with English but I come up this very easy to read.

    1. ProgrammingPot says:

      Thank You!

  35. ProgrammingPot says:

    Thank you so much!

  36. Ahaa, iits good discussion regarding this piece of writing here at this weblog, I have
    read all that, so at this time me also commenting here.

    1. ProgrammingPot says:

      Thank you for your comment.

  37. Very shortly this web page will be famous amid all blogging people, due to it’s nice content

  38. Great delivery. Outstanding arguments. Keep up
    the great work.

  39. Very nce post. I just stumbled upon your weblog andd wished to say
    that I have truly enjoyed surfing around your
    blog posts. In anny case I will be subscribing to your feed and I hope
    you write agaijn soon!

    1. Thank you so much for your great word. And Keep staying with us for my new posts.

  40. Mose says:

    Hi there mates, how is everything, and what you wish for to say on the topic of this article, in my view its truly amazing in favor of
    me.

  41. Gita says:

    Hey would you mind stating which blog platform you’re working
    with? I’m looking to start my own blog soon but I’m having a tough time selecting between BlogEngine/Wordpress/B2evolution and Drupal.

    The reason I ask is because your design seems different then most blogs and I’m
    looking for something completely unique.
    P.S My apologies for getting off-topic but I had to ask!

    1. I’m using my own design but it is fully redesigned of the WordPress. if you want the same design then I will provide for you also.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.