Showing posts with label PHP Variables. Show all posts
Showing posts with label PHP Variables. Show all posts

Monday, 5 August 2019

PHP tutorial: Variables in PHP

Variables in PHP

1) As with other programming language, PHP has the provision to define variable and manipulate
we have several types of variables in PHP,the most common used one is the string. It is use to store both the text and number
all the variable start with $ sign
Example
$tot= “This is total”;
$t1=123;
Everything inside the double quotes is assigned to the variable string tot
2) Variable names are case sensitive.so $tot and $TOT are not same
3) Variable name can contain any letters,character ,underscore but it should not start number. It cannot contain special character like #,%
Example $1=”this is not valid “; is not allowed
4) Other variable data type are integers,boolean,null,doubles,strings ,array,objects and resources
5) Variables can, but do not need, to be declared before assignment
6) Variables in PHP do not have intrinsic types – a variable does not know in advance whether it will be used to store a number or a string of characters.
$test=1;
Most other languages require that you initialize the variable before using it, specifying what type of data it can hold, but PHP is more informal. You don’t need to tell PHP which data type is in a variable. PHP evaluates the data when you assign it to the variable and then stores it as the appropriate type. Generally, this is helpful. PHP guesses the data type pretty accurately.
7) PHP does a good job of automatically converting types from one to another when necessary.
Example
<?php
$x=1;
$y=1.1;
$z= $x +$y;
echo “$z”;
?>
Here x is integer type while y is float type, while adding PHP automatically converts the integer type x to float and add the variable
8) The scope of the variable could local,global and static
Local variable are variable defined in function and there scope is limited to the function. They cannot be used outside the function
Two function can use same name of the variable as there scope will be limited to function only
<?php
function test()
{
$x=2;
echo “$x”;
}
test();
//the below statement would generate error as variable x is local to function
echo “$x”;
?>
Global variable are variable which are defined outside function. They can be used only inside the function using global keyword
<?php
$y=2;
function test()
{
$x=2;
// this will generate error global variable is not available to function
echo “$x to $y”;
}
test();
?>
<?php
$y=2;
function test()
{
$x=2;
global $y
// this will not generate error as global keyword is being used now
echo “$x to $y”;
}
test();
?>
Static variable : When the function is executed ,the local variable values are destroyed upon completion of function,but if you dont want the local variable to be deleted then use the static keyword with the local variable in the function

Friday, 2 August 2019

What is the purpose of the & Ampersand in front of PHP Variables

What this does it creates a reference to the original variable and thus does not copy the value of the original variable.
$original_var = 500;
&$ref_var = $original_var;
//This will print the value 500
echo  $ref_var;
//Now we change the value of the original variable to 600
$original_var = 600;
//Now we print the value of the reference variable, and the reference variable takes the value of the original variableecho  $ref_var;  //This will print 600
  • You can also reference objects
  • Referencing variables come in handy when trying to accomplish two task at once
NOTEPHP 5 currently supports this

Friday, 19 September 2014

PHP: Variables in PHP

Variables in PHP are quite different from compiled languages such as C and Java. This is because their weakly typed nature, which in short means you don’t need to declare variables before using them, you don’t need to declare their type and, as a result, a variable can change the type of its value as much as you want.
Variables in PHP are preceded with a $ sign, and similar to most modern languages, they can start with a letter (A-Za-z) or _ (underscore) and can then contain as many alphanumeric characters and underscores as you like.
Examples of legal variable names include
$count
$_Obj
$A123
Example of illegal variable names include
$123
$*ABC
As previously mentioned, you don’t need to declare variables or their type before using them in PHP. The following code example uses variables:
$PI = 3.14;
$radius = 5;
$circumference = $PI * 2 * $radius; // Circumference = ð * d
You can see that none of the variables are declared before they are used. Also, the fact that $PI is a floating-point number, and $radius (an integer) is not declared before they are initialized.
PHP does not support global variables like many other programming languages (except for some special pre-defined variables). Variables are local to their scope, and if created in a function, they are only available for the lifetime of the function. Variables that are created in the main script (not within a function) aren’t global variables; you cannot see them inside functions, but you can access them by using a special array $GLOBALS[], using the variable’s name as the string offset. The previous example can be rewritten the following way:
$PI = 3.14;
$radius = 5;
$circumference = $GLOBALS["PI"] * 2 * $GLOBALS["radius"]; // Circumference = ð * d
You might have realized that even though all this code is in the main scope (we didn’t make use of functions), you are still free to use $GLOBALS[], although in this case, it gives you no advantage.

Thursday, 4 September 2014

PHP Variable Types

The main way to store information in the middle of a PHP program is by using a variable.
Here are the most important things to know about variables in PHP.
  • All variables in PHP are denoted with a leading dollar sign ($).
  • The value of a variable is the value of its most recent assignment.
  • Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.
  • Variables can, but do not need, to be declared before assignment.
  • Variables in PHP do not have intrinsic types - a variable does not know in advance whether it will be used to store a number or a string of characters.
  • Variables used before they are assigned have default values.
  • PHP does a good job of automatically converting types from one to another when necessary.
  • PHP variables are Perl-like.
PHP has a total of eight data types which we use to construct our variables:
  • Integers: are whole numbers, without a decimal point, like 4195.
  • Doubles: are floating-point numbers, like 3.14159 or 49.1.
  • Booleans: have only two possible values either true or false.
  • NULL: is a special type that only has one value: NULL.
  • Strings: are sequences of characters, like 'PHP supports string operations.'
  • Arrays: are named and indexed collections of other values.
  • Objects: are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.
  • Resources: are special variables that hold references to resources external to PHP (such as database connections).
The first five are simple types, and the next two (arrays and objects) are compound - the compound types can package up other arbitrary values of arbitrary type, whereas the simple types cannot.
We will explain only simile data type in this chapters. Array and Objects will be explained separately.

Integers:

They are whole numbers, without a decimal point, like 4195. They are the simplest type .they correspond to simple whole numbers, both positive and negative. Integers can be assigned to variables, or they can be used in expressions, like so:
$int_var = 12345;
$another_int = -12345 + 12345;
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format. Decimal format is the default, octal integers are specified with a leading 0, and hexadecimals have a leading 0x.
For most common platforms, the largest integer is (2**31 . 1) (or 2,147,483,647), and the smallest (most negative) integer is . (2**31 . 1) (or .2,147,483,647).

Doubles:

They like 3.14159 or 49.1. By default, doubles print with the minimum number of decimal places needed. For example, the code:
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
print(.$many + $many_2 = $few<br>.);
It produces the following browser output:
2.28888 + 2.21112 = 4.5

Boolean:

They have only two possible values either true or false. PHP provides a couple of constants especially for use as Booleans: TRUE and FALSE, which can be used like so:
if (TRUE)
   print("This will always print<br>");
else
   print("This will never print<br>");

Interpreting other types as Booleans:

Here are the rules for determine the "truth" of any value not already of the Boolean type:
  • If the value is a number, it is false if exactly equal to zero and true otherwise.
  • If the value is a string, it is false if the string is empty (has zero characters) or is the string "0", and is true otherwise.
  • Values of type NULL are always false.
  • If the value is an array, it is false if it contains no other values, and it is true otherwise. For an object, containing a value means having a member variable that has been assigned a value.
  • Valid resources are true (although some functions that return resources when they are successful will return FALSE when unsuccessful).
  • Don't use double as Booleans.
Each of the following variables has the truth value embedded in its name when it is used in a Boolean context.
$true_num = 3 + 0.14159;
$true_str = "Tried and true"
$true_array[49] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 999 - 999;
$false_str = "";

NULL:

NULL is a special type that only has one value: NULL. To give a variable the NULL value, simply assign it like this:
$my_var = NULL;
The special constant NULL is capitalized by convention, but actually it is case insensitive; you could just as well have typed:
$my_var = null;
A variable that has been assigned NULL has the following properties:
  • It evaluates to FALSE in a Boolean context.
  • It returns FALSE when tested with IsSet() function.

Strings:

They are sequences of characters, like "PHP supports string operations". Following are valid examples of string
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables with their values as well as specially interpreting certain character sequences.
<?
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
$literally = "My $variable will print!\\n";
print($literally);
?>
This will produce following result:
My $variable will not print!\n
My name will print
There are no artificial limits on string length - within the bounds of available memory, you ought to be able to make arbitrarily long strings.
Strings that are delimited by double quotes (as in "this") are preprocessed in both the following two ways by PHP:
  • Certain character sequences beginning with backslash (\) are replaced with special characters
  • Variable names (starting with $) are replaced with string representations of their values.
The escape-sequence replacements are:
  • \n is replaced by the newline character
  • \r is replaced by the carriage-return character
  • \t is replaced by the tab character
  • \$ is replaced by the dollar sign itself ($)
  • \" is replaced by a single double-quote (")
  • \\ is replaced by a single backslash (\)

Here Document:

You can assign multiple lines to a single string variable using here document:
<?php

$channel =<<<_XML_
<channel>
<title>What's For Dinner<title>
<link>http://menu.example.com/<link>
<description>Choose what to eat tonight.</description>
</channel>
_XML_;

echo <<<END
This uses the "here document" syntax to output
multiple lines with variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon. no extra whitespace!
<br />
END;

print $channel;
?>
This will produce following result:
This uses the "here document" syntax to output
multiple lines with variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon. no extra whitespace!

<channel>
<title>What's For Dinner<title>
<link>http://menu.example.com/<link>
<description>Choose what to eat tonight.</description>

Variable Scope:

Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types:
  • Local variables
  • Function parameters
  • Global variables
  • Static variables

Variable Naming:

Rules for naming a variable is:
  • Variable names must begin with a letter or underscore character.
  • A variable name can consist of numbers, letters, underscores but you cannot use characters like + , - , % , ( , ) . & , etc
There is no size limit for variables.