Variable Welcome! A variable is a mean to store values such as strings or integers so we can easily reuse those values in our code. For example, we can store a string value such as "I Love PHP" or an integer value such as 100 into a variable. When ever we need to use these values, we simply call that variable instead writing out those values over and over again in our code. Here is an example. <?php $str="I love PHP"; //here is one variable with a string value echo $str; // here we print the $str value onto the browser $num = 100; //another variable with a integer value echo $num; // here we echo the $num variable to print its value echo $str; //here we reuse the $str variable to print its value again in our code echo $num; //here we reuse the $num variable to print its value again in our code ?> The following code should print "I Love PHP100I Love PHP100". Try it. Copy the code in an empty file, save the file as php and run it on your browser. Variables in PHP Every language has its own semantics of defining variables. In PHP, we define a variable starting with a $ sign, then write the variable name and finally assign a value to it. Here is an example below. $variable_name = value;
You must add the $ sign when declaring variables, otherwise it
will not work. It is advisable that when you define a variable,
you must initilaize it by assign it a value.
Working With PHP Variables Few Naming Rules There are few things we need to note when working with PHP variables.
Declaring a PHP Variable Let say we want to store values using variables in PHP. Here's how we do it.
Let's look at some example... PHP String Variable Example - PHP variable with a string value <?php $logo_text = "PHP-Learn-It! Learn PHP by examples"; echo $logo_text; ?> In the above code we define a variable name $logo_text, assign it a string value "PHP-Learn-It! Learn PHP by examples" and print its value onto the page. PHP Integer Variable Example - PHP variable with an integer value ?php $number = 100; echo $number; ?> In the above code we define a variable name $number, assign it an integer value of 100 and print its value onto the page. PHP Float or Decimal Variable <?php $decimal_number = 100.01; printf("%.2f", $decimal_number); ?> In the above code we define a variable name $decimal_number, assign it a decimal value of 100.01 and print its value onto the page. Summary Some key points to remember when declaring variables in PHP
|