How to use variables (PHP 7)

Coding (Php 7.x)


Variables do not cause headaches only to beginners, learn to use variables as an expert.
 
/img/blog/php-variables.jpg

Introduction

We all look for a shortcut to get faster where we want to go,

 

Who has never quickly flip through some pages of a book or even go straight to the last chapter?

 

Although this may seem like a good idea at the beginning, I've already shared in several blog posts multiple reasons why a gradual improvement is much better and more productive than going straight to fun things.

 

The truth is, if you want to code for several years and do not burn out in the first years or even months of a career as a web developer you have to study the basics,

 

I tell you a secret, 
even when, after years of experience, when you believe that there is nothing you do not know about a basic topic, pick up the first book or one of the first articles you read, you will always find a paragraph that you did not pay attention to or a concept that you did not fully understand before.

 

This post, in fact, is for everyone.

As beginners, they are just starting their journey with PHP to expert programmers who will discover features of the code they did not know.

Even on a basic topic like what we're going to see below,

 

Here, in fact, there is general and detailed information on variables in PHP.

I'll give you some helpful insight on what are and how to declare and use variables in the best way for your web applications.

 

This post is part of the series "PHP basics for expert programmers" click on the links below for other posts published so far.
PHP basics for expert web developers (1' part)
Construct and Comments of PHP 7
How to use variables (PHP 7)
Composite variable in PHP (Arrays, Object and more)
PHP Operators (Part 1)
PHP Operators (Part 2)
Conditional Structures in PHP
Loops in PHP(Tutorial)

 

 

 

 

 

Variables


When writing a program, whether it is a simple to-do list or an integrated payment system for a bank that has clients worldwide you are going to need to use variables.


Variables are used to store data.

Think of variables as if they were boxes.

 

In every programming language, a "box" has a name written on the outside which is the name by which the box is called and a "thing" inside.

 

As said every box (variable) has a name, when we give a name to the box and define what is inside it we say that we assign a value to a variable.

 

There are different types of "things" that a box can have inside,

the variables are in fact divided into three main categories:
scalar type variables, composite variables and resources.

 

The scalars are the most basic and easy to understand.

 

They are divided into:

 

The composites ones are a bit more complicated but nothing impossible,

they are:

  • Arrays
  • Objects
  • Callables
  • Iterables

 

Then we have resources, which can be seen simply as, for example, objects external to PHP as files, database connections.

 

Finally,

we have the NULL type, which is used for variables that do not have an assigned value,

it is not possible to transmit to a NULL type but it is possible to assign a value of NULL to a variable.

 

Now,

PHP is a loosely-typed language, which means that a variable can change its contents during runtime.

In fact,

the value can change from string to integer to boolean without creating any problem with the script and even without throwing any errors.

 

When it comes to variables, a fundamental part to understand is the so-called casting,

that is, how the variable is seen by the programming language.

 

As you've seen, in PHP variables can change type and understand how these changes happen behind the scenes is an essential part of the work of a web developer (not to mention the number of migraines that you will avoid).

 

Imagine that you have a type-string variable $str containing "10",

imagine that, a couple of lines below you sum the variable with another number,

let's say

$str = "10";
$num = $str + 5;
// $num will take the value of 15

 

PHP is smart enough to understand that the intention was to add the number 10 contained in the string with the number 5.

 

The operation will parse successfully without errors and the value of $num will be 15.

 

The reasoning that PHP does is called "casting" and I am sure you already understood that it is a powerful ace in our sleeve but at the same time can easily turn into a double-edged sword.

 

You will see all kinds of variables and their declarations below, for further information I invite you to take a look at the official manual.

 

 

Boolean variables

Understanding how the Boolean variables work is the easiest thing in programming.

 

A boolean variable indicates only one bit, thus only two values:
1 or 0, it can be true or false, yes or no,
there is no other alternative,

 

Boolean is the value that is considered during conditional statements like if, else, and cases of the switch-case.

 

There are several rules to keep in mind regarding casting on Boolean variables.

 

Empty arrays are counted as 0 or false;
unless you consider empty stings, they are always considered true;
if a string contains the number 0 the Boolean value is considered 0 or false;
if a string contains any other number when cast as a boolean the value becomes true;
every integer or float that does not have the value of 0 is to be considered true, this means that a negative value is true as well.

 

The guys at techterms.com have created a brief explanation of what Boolean means and how it can be used on search conditions and search engines

Check their definition

 

 

Integer variables

Integers are all the numbers that belong to the whole-number category.

 

For integers, I intend all the negative and positive 0 included.

 

Are also to be considered integer numbers in bases different from 10,


in fact,

in PHP you can use numbers based on binary, octal, decimal, and hexadecimal;

 

You must use a prefix that will set the type of base you want to use

 

0b indicates numbers based on binary,

"0b1100100" represents the value 100 in base 2,

 

0 followed by a number indicates that the number is to be considered octal

100 (base 10) becomes 0o144 in base (8).

 

The prefix to use what you intend to indicate hexadecimal numbers instead is' 0x
0x64 is the hexadecimal value to use for 100 (base 10).

 

The range of numbers available depends on how powerful your computer is.

 

The maximum value that variables of type integer can have is 2 billion (for PC running 32 bit) and about 9E18, yes 18 zeroes, for 64-bit platforms.

The maximum value of type integer in 64-bit platform is 1000000000000000000

 

You can modify this limit using constants like PHP_INT_SIZE, PHP_INT_MAX and PHP_INT_MIN.


But unless you work for Elon Musk and you are in charge of developing the software that will make us land on Mars I really discourage their use.

(if you are and you have decided to use PHP, well, good luck with that).

 

To be honest, it is possible to overcome this limit without using the constants but the variables will no longer be considered as integers but will be transformed into floats,

 

here is an example available in the official manual of PHP:

$number = 2147483647;
// this is an integer on 32-bit machines
$number = 2147483648;
// this is a float on 32-bit machines

You can also cast variables and make them integer using the keywords (int) or (integer) followed by the number you intend to cast.

 

Note also that when you cast a value to integer PHP does not round above or below but simply cuts the portion of the decimal number

100.57 becomes 100
-100.57 becomes -100

 

when you cast a string in an integer, it will give 0 unless the string starts with a number

 

"10 o 'clock" becomes 10;
"half past 10" becomes 0;

 

Last note to consider is dealing with irrational numbers.

look here,

echo (int) ((0.1 + 0.7) * 10);

 

Would you expect that the result would be 0.8 right?
not exactly.

The values echoed would be 0.7.
0.7 can be expressed as a rational number based on decimal but not on base 2.

 

Since there is only a limited number of bits available to be saved it is inevitable that there is a loss of precision during these calculations.

 

To be clear the internal representation of the code above will be something like 7.9999999999999991118...

 

The degree of accuracy depends on the machine on which PHP runs,
below there is a small snippet created by Andrew Beak that allows you to check the accuracy level of your system.

 

This value is known as the machine epsilon, or unit roundoff, and is the smallest acceptable difference in calculations.

$pi = 3.14159625;
Indian $ = 3.2;
$epsilon = 0.00001;

if (abs($pi - $Indian) < $epsilon) {
    echo "Those values look the same";
} else {
    echo "Those values are different";
}

 

This code checks if the values are equal to five degrees of precision.

 

 

Float variables

Unlike integer, float or double numbers are all numbers that are not whole-number,

 

To make it simple, the numbers that have a comma are to be considered float.

 

Although, as for the integer, the range of these variables depend on the power of the platform on which we work, PHP uses a standard called IEEE 754 in order to limit errors to a minimum.

 

We have already seen however that for values such as 0.1 and 0.7 there is no exact representation which involves some issues.

 

As regards the conversion of float variables, the procedure is rather simple and depends on the type of source variable.

 

To integer the procedure is almost natural, just add 0.n to the number and there you go! here is a float or double number.

 

The procedure on strings is a bit more complicated but there will be no errors if you continue to follow the rules and the string contains appropriate values.

$var = 10 + "100.3";                
// $var is afloat and its value is 110.3
$var = 7 + "11.2 kg of ham"; 
// $var is a float and its value is 18.2

 


String variables

After describing variables that contain numbers, now let's talk about variables that contain characters,

 

A character is worth one byte, which means that PHP has only 256 character characters available.

 

PHP strings are a series of bytes.

 

The information stored inside PHP  regarding strings are their length and the content,


32-bit systems support strings as large as 2GB whereas 64-bit systems do not have any particular limit.

 

A string can be declared using two different methods,

the simple method does not evaluate control characters and variables and the complex method that takes into account variables' value.

 

To use the simple method you need to use the single-quote-marks while for the complex you would use the double-quote-marks

$language = 'PHP';
$simple = 'I code in $language';
echo $simple;
// The string echoed will be: I code in $language
$complex = "I code in $language";
echo $complex;
// The string echoed will be: I code in PHP 

As you can see the double quotes evaluates the $language variable and show its actual value.

 

This is a huge advantage because let you create complete strings of text without the necessity of using concatenation, which in my opinion make the code much simpler to read

$city = 'London';
echo 'I am a Web Developer based in ' . $city;
echo "I am a Web Developer based in $city";

 

Did you see what I mean?

 

A little tip that I use some time to specify to the PHP parser that I want to evaluate a variable is to use curly braces.

 

$burger = "hamburger";
echo "I love $burgers";
// I love $burgers
echo "I love {$burger}s";
// I love hamburgers

 

Since $burgers is not a defined variable, in the first example PHP will not evaluate it and show a plain string, in the second example the curly braces indicate that you want the variable to be evaluated so it will be shown in a plural context.


You will see that there are more examples of proficient use of curly braces with strings such as using them when evaluating data within arrays and objects. 

 

 

Conclusion

 

As you have also seen a basic element of programming as the variables have so much to hide and must be deepened in such a way as to be fully understood.

 

In this blog post, we focused on scalar variables, which are the most common and elementary variables,

 

Stay tuned,
In the next episode of the series, we're going to study composite variables like null array objects and resources.


But,

if you want to have a preview now here is a video that can work for you.

 

 

PHP basics for expert web developers (1' part)
Construct and Comments of PHP 7
How to use variables (PHP 7)
Composite variable in PHP (Arrays, Object and more)
PHP Operators (Part 1)
PHP Operators (Part 2)
Conditional Structures in PHP
Loops in PHP(Tutorial)

 

 

Now that you understand this other basic concept of PHP it's time to practice and start creating your own brand online.

 

You can do it now with hosting services like Blue Host that allows you to create an account and put your work on the worldwide showcase that is the internet.

(This is an affiliate link, The price stays the same for you and it helps me improve this content.)

 
 
If you like this content and you are hungry for some more join the Facebook's community in which we share info and news just like this one!

Other posts that might interest you

Coding (Php 7.x) Dec 16, 2018

Construct and Comments of PHP 7

learn more See details
Coding (Php 7.x) Jan 2, 2019

Composite variable in PHP (Arrays, Object and more)

Get the full article See details
Coding (Php 7.x) Jan 7, 2019

PHP operators (part 1)

Get the extra See details
Get my free books' review to improve your skill now!
I'll do myself