Hands-on with PHP — Variables

< Home < PHP Data TypesPHP Outputs >

Containers for Data

You have explored data of the various types in the Data Types lesson. Those data are literal and transient, which means they cannot live beyond the piece of code that created them.

<?php
echo "Host: Could you tell me your name?<br>";
echo "Guest: My name is Peter Leow.<br>";
echo "Host: Welcome, Er... What is your name again?";
?>

More often than not, however, the same data is needed to be re-used for further processing in a computer program. To keep the data available, it must be stored in a computer memory during the lifetime of the program execution. In computer programming, this is achieved by assigning the data to a variable which acts as a reference to a computer memory address that stores the data. This variable is given a human-readable name that reflects the meaning of the data that it is assigned. You may liken a variable to a container that is labeled, and the data to the content that is stored in it.

In PHP, a variable must starts with a $ prefix, followed by the name of the variable, e.g. $guest_name. You can then assign a string, say "Peter Leow", to this variable via an assignment operator =, e.g. $guest_name = "Peter Leow".

<?php
// Assign the literal string "Peter Leow" to a variable called $guest_name
$guest_name = "Peter Leow";
echo "Host: Could you tell me your name?<br>";
echo "Guest: My name is $guest_name.<br>";
echo "Host: Welcome, $guest_name.";
?>

Syntax for PHP Variables

PHP variables must follow a set of rules as follows:

  • Variables must start with a $ prefix, followed by the name of the variable.

  • Variable names must start with an alphabet (a-z, A-Z) or an underscore (_), followed by any number of alphabets, digits (0-9), or underscores.

  • Variable names are case-sensitive, i.e. $guest_name and $guest_Name are two different variables.

Note:

There is an exception — `$this` is a pseudo-variable reserved for referencing the calling object of a method in object-oriented programming. You cannot assign any value to it.

The code in the Variable Syntax code section is erroneous, fix it!

<?php
$guest_name = "Peter Leow";
echo $guest_Name;
?>

Naming PHP Variables

How would you label the many containers that contain different types of item? Do you simply label them x, y, or z? Or do you label them according to the types of item that they carry, such as cookie or candy? Which one of them allows you to locate the container that contains the type of item that you are looking for easier and faster? You bet!

Every data has its meaning, it pays to choose a name that reflects and describes this meaning explicitly for its variable. Not only does this practice make your code more legible, but also easier to maintain. For example, if a variable is to store the name of a customer, should you name it $x, $name, $customer, or $customer_name? I hope you have chosen $customer_name.

For variable names that consist of multiple words, you can either separate these words with underscores, such as $customer_name, or join these words but capitalize the first letter of words except the first one, such as $customerName. Whichever the choice may be, it has to be set as a standard convention that all members of the development teams follow strictly.

Variable Types

In PHP, you do not declare variable type explicitly. A variable automatically adopts the data type of the value assigned to it implicitly. This is an example of the so-called type juggling in PHP.

<?php
echo "<pre>";
// String variable
$title = "Hands-on with PHP";
echo '$title is ', var_dump($title);

// Boolean variable
$truth = true;
echo '$truth is ', var_dump($truth);

// Integer variable
$age = 12;
echo '$age is ', var_dump($age);

// Float variable
$salary = 1200.50;
echo '$salary is ', var_dump($salary);

// declare a class
class Student {
  public $name;
  function Student($new_name) {
  $this->name = $new_name;
  }
}
       
// Object variable
$new_student = new Student("Peter Leow");
echo '$new_student is ', var_dump($new_student);

// Array variable
$week = array("Mon","Tue","Wed","Thu","Fri","Sat","Sun");
echo '$week is ', var_dump($week);

// NULL variable
$undefined = NULL;
echo '$undefined is ', var_dump($undefined);

// Resource variable
$file = fopen("https://peterleowblog.com/wp-content/uploads/2017/10/textfile.txt", "r");
echo '$file is ', var_dump($file);

echo "</pre>";
?>

Type Juggling

Type juggling in PHP allows automatic conversion of any variable or value from one data type to another implicitly based on the context of the evaluation.

One usage of type juggling is the variable’s automatic and implicit adoption of the data type of its value mentioned above. With automatic and implicit type assignment, it becomes possible that a variable can switch from one type to another the moment a value of different data type is assigned to it.

Another usage of type juggling is the automatic and temporary type conversion of any variable or value during evaluation based on the context of the evaluation, such as the addition between a numeric string and an integer number, e.g. "2" + 3, where the "2" is interpreted as integer for addition operation. However, this usage does not change the original data type of the operand, i.e. "2", only how it is being intepreted during the evaluation.

<?php
echo "<pre>";
$variable = "A";
echo '$variable is ', var_dump($variable);
$variable = 8;
echo '$variable is ', var_dump($variable);
/*
$variable is string(1) "A"
$variable is int(8)
*/
echo "\n";
$string = "2";
$integer = 3;
echo '$string is ', var_dump($string);
echo '$integer is ', var_dump($integer);
echo "\"$string\" + $integer = ", var_dump($string + $integer);
echo '$string is ', var_dump($string);
echo '$integer is ', var_dump($integer);
/*
$string is string(1) "2"
$integer is int(3)
"2" + 3 = int(5)
$string is string(1) "2"
$integer is int(3)
*/
echo "</pre>";
?>

Variable Variables

A variable variable is a variable that takes the value of another variable as its name. For example, the following statement creates a normal variable:

$variable = "salary";

Prefix a $ to $variable above turns it into a variable variable called $$variable as shown:

$$variable = "1000";

$$variable creates a new variable that is named after the value salary in $variable, resulting in a new variable as shown:

$salary = "1000";

Check out the example in the Variable Variables code section using the PhpFiddle widget.

<?php
$variable = "salary";
$$variable = "1000";
echo "$$variable = $salary";
/*
$salary = 1000
*/
?>

As you can see, using variable variables you can create new variables that are named after values of other variables on the fly. With that in mind, variable variables come in handy when you need to store elements of an array in separate variables. Without using variable variables, you will have to create a variable for each element as shown in the following example:

$contact = array("mike"=>"546-9442", "rex"=>"446-8851", "steve"=>"925-1352", "james"=>"906-2721", "jeff"=>"569-4371");
 $mike = $contact["mike"];
 echo "\$mike = $mike\n";
 $rex = $contact["rex"];
 echo "\$rex = $rex\n";
 $steve = $contact["steve"];
 echo "\$steve = $steve\n";
 $james = $contact["james"];
 echo "\$james = $james\n";
 $jeff = $contact["jeff"];
 echo "\$jeff = $jeff";

The code above will output the following result:

$mike = 546-9442
$rex = 446-8851
$steve = 925-1352
$james = 906-2721
$jeff = 569-4371

Assign variable names this way becomes infeasible, however, for arrays that are created on the fly or when the number of elements is too huge. Instead, rewrite the code above using variable variables and foreach loop as shown below:

$contact = array("mike"=>"546-9442", "rex"=>"446-8851", "steve"=>"925-1352", "james"=>"906-2721", "jeff"=>"569-4371");
  foreach ($contact as $name => $phone) {
  $$name = $phone;
  echo "$$name = ${$name}\n";
}

In the rewritten code above, the variable variables is the $$name. Run the rewritten code in the Variable Variables Application code section using the PhpFiddle widget and see that it outputs the same results as that outputted by the original code:

<?php
$contact = array("mike"=>"546-9442", "rex"=>"446-8851", "steve"=>"925-1352", "james"=>"906-2721", "jeff"=>"569-4371");
foreach ($contact as $name => $phone) {
  $$name = $phone;
  echo "$$name = ${$name}<br>";
}
/*
$mike = 546-9442
$rex = 446-8851
$steve = 925-1352
$james = 906-2721
$jeff = 569-4371
*/
?>

Any Other Matters

  • The value of variable can be changed during the course of a program execution as shown in the Changed Variable Value code section:
<?php
$level = 8;
echo $level;
echo "<br>";
$level = $level + 1;
echo $level;
?>
  • Similarly, the data type of a variable can be changed during the course of a program execution as shown in the Multi-Type Variable code section: , but such a practice should be avoided at all costs, as not only does it make your code harder to read and maintain, it also leads to programming errors easily.
<?php
echo "<pre>";
$multi_type_variable = "Peter Leow"; // String
var_dump($multi_type_variable);
$multi_type_variable = TRUE; // Boolean
var_dump($multi_type_variable);
$multi_type_variable = 12; // Integer
var_dump($multi_type_variable);
echo "</pre>";
?>
  • Last but not least, the accessibility of a PHP variable in a program depends on where and how it is created. This is called the variable scope, the learning of which is deferred until after the lesson on Functions. So, stay tuned!

Quiz

How do you determine the correct data types for those data involved in a software application? Sometimes the obvious is not always so obvious! Some of the considerations include the context of the data and the types of usage required or not required of the data in accordance with user requirements. Check these questions out and ask yourself why you choose a particular answer.

Are PHP variables case sensitive?
Yes.
Correct!
No.
Wrong!
Which one of the following strings is a valid PHP variable?
$student_id
Correct!
studentid
Wrong!
$student-id
Wrong!
$2student_id
Wrong!
<?php 
$x = 12; // years of service of an employee
?>
How would you improve the code in Listing 1?
$employee_year_of_service = 12;
Correct!
$year_of_service = 12;
Wrong!
$year = 12;
Wrong!
$yos = 12;
Wrong!
<?php 
$is_married = TRUE; // marital status
?>
What is the most appropriate data type for $is_married in Listing 2?
Boolean
Correct!
Integer
Wrong!
String
Wrong!
Float
Wrong!
<?php 
$age = 5;
$age = $age + 1;
echo $age;
?>
What is the expected output value of the variable $age from the execution of the PHP code in Listing 3?
6
Correct!
5
Wrong!

< Home < PHP Data TypesPHP Outputs >

Tagged with:

Speak Your Mind