Exploring Data Types, Variables and Operators in PHP

In PHP or any programming language, a data type is an attribute of data that tells the interpreter how the programs intend to use the given data. PHP supports a couple of data types of which are integer numbers of varying sizes, characters, Booleans, Floating point number to mention a few.

A data type can’t hold itself, and so, we need a certain type of container or a memory location that stores the value. An example of such is a variable.

Variable can be thought of as a memory location that can hold values of a specific data type, the name “variable” means something that is likely to vary or something that is subject to variation, so, with that meaning, we can say a variable may change during the life of the program.

Before we get deep into a variable and the data types. there are rules or conventions about the names that we can give to a variable, so, let’s look into that first.

Variable Naming Convention in PHP

  • A valid variable name starts with a dollar sign followed by a letter or underscores.
  • They can be followed by numbers, underscores, or dashes.
  • They can’t contain any space, and they are case sensitive, meaning $book is different from $Book

PHP is a loosely typed language, which means a single variable can contain any type of data, string, boolean, etc. Unlike other languages where you need to first declare what the variable would do, you don’t need that in PHP, just store your variable away, and use it how you see fit.

Variable Examples

Let’s see a couple of examples:

					

<?php
$var = 'Hello';
$Var = 'World';
echo "$var, $Var";      # This outputs "Hello, World"

3book = 'Hi';           # This would print an error, no dollar sign, and variable does not start with number
$3book = 'Hey';         # This would print an errro, variable does not start with a number
_3book = 'I love you'; # This is wrong, a variaable does not start with an underscore

?>

If you recall in the variable naming convention section, I said variable namings are case sensitive, which is why $var and $Var means a different thing (see the example above). You actually don’t have to use a variable that has a similar name, you need to give the variable a meaningful name, this way, you know what is what, the above is just to prove to you that variables are case sensitive.

We can also have myVariablewith a capital V, which is often referred to as camel case, because the uppercase letters in the middle are like the humps in a camel. It looks fancy, and that’s probably the reason why some devs love structuring their variables that way. This is totally optional, I am just showing you in the hope that you come across it.

You can also have variables like this:

$my_variable
$my-variable
$my_variable3
$my-variable6

All of the above are perfectly valid, you can even go as far as putting underscores in front of the variable or at the end of the variable, e.g

$_myvariable
$myvariable_

The above variables are also valid, but most times I would advise you to keep things simple to avoid confusion down the line. In short, I don’t have underscores or minus included in my variables, it is just too confusing, and can lead to you hitting your head on the wall when an error occurs in a big project. So, you might as well start keeping your naming simple right off the bat.

Also, there are a couple of reserved words in PHP that you are not allowed to use as they have there on meaning, it isn’t actually true that you can’t use reserved keywords, you can use them but it is advisable to stay away from them as much as possible as this keywords can not only lead to confusion but also cause a malfunction in your projects, here are the list of reserved keywords:

'__halt_compiler', 'abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use', 'var', 'while', 'xor'

Okay, cool, we are making progress. Let’s see how variable works in a real-life example, create a php file e.g example.php, and add the following:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>A Variable Example</title>
</head>
<body>
<?php
$string1 = 'Hello';
$string2 = 'World';
echo "$string1, $string2";      # This outputs "Hello, World"
echo "<br>";
echo "<br>";

$num1 = 5;
$num2 = 5;

$totalnum = $num1 + $num2;
echo $totalnum;          # This prints "10"
?>
</body>
</html>

The output is:

Hello, World

10

As you can see, the above is a standard HTML syntax mixed with PHP, so, all I did there is adding php within the body (<body> … </body>) of the HTML. The webserver would interpret the PHP within the body, and convert it to a regular HTML code before it sends the webpage to the requesting web browser.

So, we store “Hello” and “World” in a different variable, we then output it using the echo command, we also did a simple calculation by adding two variables together, storing the result in another variable, and then echoing it.

Here are a couple of more examples:

Note: We would talk more about interger number and calculations in a later section

					

$myVar = 1 + 1; # Add up 1 + 1, and stores the result 2 in $myVar
$myVar = 1 - 1; # Substract 1 - 1, and stores the result 0 in $myVar
$myVar = 2 * 2; # Multiple 2 * 2, and stores the result 4 in $myVar
$myVar = 2 / 2; # Divide 2 / 2, and stores the result 1 in $myVar

A variable can be used anywhere as you have seen in the HTML example above, but here are some more examples:

					

$myvar1=5; # Stores 5 in $myvar1
$myvar2=$myvar1 + 5; # Add the value of $myvar1 with 5, and stores it in $myvar2
$myvar3=rand(1, 12); # Assigns a value to $myvar3 using the random function
$myvar4=$myvar3; # Copy the value of $myvar3 to $myvar4

Strings

A string is an example of data type, and is a very common feature of most programming languages, including PHP, well, we’ve used strings in the above example, but you might not be aware.

A string is a series or set of characters, where characters can be letters, numbers, symbols, and can be defined inside quotation marks, e.g single quotes or double-quotes or you can also specify them using heredoc syntax or nowdoc syntax, which we would cover below.

Another way of seeing string is by text.

Let’s see an example when using a single quotes:

					

<?php
echo 'A String'; # This would output "A String"

#
# To Write a certain strings on a new line, you do it this way
#
# Note: This has a couple of issues when rendering in the browser
#
echo 'To add a string on a new line
you do it like the way I am 
do it';

#
# If you have a single quote in the world you want to
# output, e.g I'll Call You Back
# You use a backslash
#
echo 'I\'ll Call You Back';

#
# To output an actual backslash, then you add multiple backlsah
# e.g to get: This would output only one backslah \
# You do this:
#
echo 'This would output only one backslash \\'; 

#
# Note: Escape sequence won't expand if a string is in a single quote
# e.g
#
echo 'This will not expand: \n a newline';

# Any variable in a single quote won't expand the variable either
echo 'It won\'t expand the following variables $myString $myVar';
# You would get the following output:
# It won't expand the following variables $myString $myVar

Let’s see an example when using a double quotes:

Note: If a string is enclosed in a double quotes, PHP will interpret the escape sequences for special characters, I won’t list them all, but here are the most popular used ones:

Sequences and Their Meaning

\n This advances to the next newline e.g

echo "Hello \nHow You Are ? ";

gives

Hello 
How You Are ?
\t Horizontal tab e.g

echo "\tHello, How You Are ? ";

gives

	Hello, How You Are ?
\v Vertical Tab,
\\ Backslash. e.g

echo "Hello, How Are You \\? ";

gives

Hello, How Are You \?
\$ Dollar Sign, e.g

echo "I have \$20,Million!";

gives

I have $20,Million!

Without the backslash, it would think it is a variable

\” Double quotes, e.g

echo "Learn Enough To Be Dangerous - \"Author\"";

gives

Learn Enough To Be Dangerous - "Author"

The most important feature of double-quoted strings is the fact that variable names will be expanded.

Let’s see an example by mixing HTML with PHP:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Strings Example</title>
  </head>
  <body>
  <?php
  
  echo "Hello Fred<br>";
  echo 'Welcome To Devsrealm<br>';

  $myString1 = "Hello";
  $myString2 = "World";
  $phrase = "$myString1 " . "$myString2";
  echo $phrase;
  ?>

  </body>
</html>

Output is:

Hello Fred
Welcome To Devsrealm
Hello World

The first (Hello Fred) and second (Welcome To Devsrealm) example simply create line breaks between them,  the <br> element produces a line break.

In the third example, we store “Hello” and “World” into two different variables ( $myString1and $myString2), we then concatenate the string using the dot (.), this is called the string concatenation operator, it sticks strings of text together.

You can also concatenate this way:

$phrase = $myString1 . " " .$myString2;

As you can see, we added a space in the two quotes, which would give us: “Hello World”

If you look at the example carefully, you’ll see the variables are in double-quotes, so anything inside the variable would be expanded, but you should note that if you place a variable inside a single quote, it will only print the string rather than the value in the variable, and if you used a double-quote, the variable in the string is replaced with the variable content.

Before we go into the next section, let me quickly show you another way you can do a variable replacement, consider the following example:

					

<?php
$bk = "book";
echo "We currently have 15 $bks in the library";

In the above example, we stored book into the variable $bkand if you look at the following we output the string, you might expect this to work, but this won’t work because PHP interpreter would consider $bksa variable, but the actual variable is $bk.

So, here are a couple of ways to solve the problem:

					

<?php
$bk = "book";
#
# Method One
#
echo "We currently have 15 $bk s in the library\n\n";
// Output is: We currently have 15 book s in the library

#
# Method Two
#
$bk = "book";
$str='s';
echo "We currently have 15 $bk$str in the library\n\n";
// Output is: We currently have 15 books in the library

#
# Method Three
#
$bk = "book";
echo "We currently have 15 {$bk}s in the library";
// Output is: We currently have 15 books in the library

As you can see, the method 1 is a no no. Method 2 requires us to assign a new character to a different variable before we can output it in the correct format.

Method 3 is the best method as it allows us to separate the variable name and the characters inside a string, as you can see this is done using the curly braces.

So, why use this at all? Well, it gives you flexibility when outputting variable values in a specified way, like in the example above, there might be a place in your code when you need to only use bookand there might also be places in your code when you need to use books(as in plural), this avoids unnecessary assignment of variables.

Also, it serves as a superb substitution for concatenation, they are quicker to type and code looks cleaner, so whenever you want to separate a variable name and the other characters inside a string, you can use curly braces.

Note: The reason why I mention the feature above is that you might come across it, so, now you know how it works.

Let me just drop this here, you can also concatenate string the following way:

					

$myString1 = "Welcome To Devsrealm. ";
$myString2 = "You'll Learn a Lot Here";
  
$output= $myString1 ;
$output.= $myString2;
echo $output;

// Output is: Welcome To Devsrealm.You'll Learn a Lot Here

The above is another way you can concatenate a string, we told PHP, hey PHP, we’ve already store $myString1 into the variable $ouput, could you please append the string $myString2 to it, and that is why we have the line: $output.= $myString2;

It is as simple as that!

String Function

Up until now, we’ve seen the echo and the rand command, there are a couple of functions that could do wonder to your strings, and they are as follows:

					

<?php
$myString1 = "Welcome To Devsrealm. ";
$myString2 = "You'll Learn a Lot Here";

$output= $myString1 ;
$output.= $myString2;

#
# Example 1: Lowercase
#
# The Output of below is: welcome to devsrealm. you'll learn a lot here
#
echo strtolower($output); ?><br>

<?php
#
# Example 2: Uppercase
#
# The Output of below is: WELCOME TO DEVSREALM. YOU'LL LEARN A LOT HERE
#
echo strtoupper($output); ?><br>

<?php
#
# Example 3: ucfirst (This makes the first letter uppercase)
#
# Since some of the strings are already in a Sentence Case,
# We need to first convert everything to lowercase first.
# We then use ucfirst, this makes sense as ucfirst only looks at the first character
#
# The Output of below is: Welcome to devsrealm. you'll learn a lot here
#
echo ucfirst(strtolower($output)); ?><br>

<?php
#
# Example 4: ucwords (This makes the words uppercase)
#
# The Output of below is: Welcome To Devsrealm. You'll Learn a Lot Here
#
echo ucwords($output); ?><br>

There is really not much to say, but the only thing you should note is functions often take some parameters as an argument.

They take something as input into the function, and then they return output to you, in the case of this:

echo strtolower($output);

The function to strtolower takes the result of the variable $output into the function, and it then returns the result when it is done with the processing, in which we get: welcome to devsrealm. you'll learn a lot here

Let’s see more examples:

					

<?php
#
# Example 5: strlen (This Finds the length of the sring)
#
# The Output of below is: Welcome To Devsrealm. You'll Learn a Lot Here
#
echo strlen($output); ?><br>

<?php
#
# Example 6: trim (Strip whitespace (or other characters) from the beginning and end of a string)
#
# The Output of below is: AB C DE
#
echo "A" . trim(" B C D ") . "E"; ?><br>

<?php
#
# Example 7: strstr (Find the first occurrence of "Devsrealm" (this is known as needle) in the string
#                   return it and the rest of the string)
#
# The Output of below is: Devsrealm. You'll Learn a Lot Here
#
echo strstr($output, "Devsrealm"); ?><br>

<?php
#
# Example 8: str_replace ( Replace all occurrences of the search string with the replacement string)
#
# The Output of below is: Guys. You'll Learn a Lot Here
#
# This search for "Welcome To Devsrealm" and replaces with "Guys" handy hun (:
#
echo str_replace("Welcome To Devsrealm", "Guys", $output); ?><br>

I have added commentary in the above code, so, that should explain it. If you look at example 8, you’ll see that it takes three arguments, which are “What we are searching for”, “What we want to replace it with”, and “Where are searching it”, the order of this is very important, so, take note.

Let’s see more examples, I promise this would be the last example on strings:

					

<?php
#
# Example 9: str_repeat (This would repeat the founded string)
#
# This would repeat "Welcome To Devsrealm. You'll Learn a lot Here" 3 times
#
echo str_repeat("$output", "3"); ?><br>

<?php
#
# Example 10: substr (This returns a part of a string.)
#
# In this example, we tell it to start at 3, note that the counting begins at 0, so 0 - 3 is 4
# And the 4th character is c, so, now that we know where to start, we can optionally specify the length of
# String to return, in this case it is 5, so, Welcome To, returns come . You might wonder why it isn't comeT,
# This is because it counts the length as well.
#
# If we didn't specify the length, it would return the start of where you tell it to start through the end of the string.
# e.g you get "come To Devsrealm. You'll Learn a Lot Here"
#
# if the start location is -3 and no length argument is specified, the last 3 characters of the string are returned:
# e.g you get "ere"
#
echo substr("$output", -3); ?><br>

<?php
#
# Example 11: strpos (This would tell us the position of a given string)
#
# The Output of below is: 11, which means the string "Devsrealm" is in position 11
#
#
echo strpos("$output", "Devsrealm"); ?><br>

<?php
#
# Example 12: strchr (This would tell where a certain character is located)
#
# The find characater that it would come across is D, it then output the rest of the string, e.g
# Devsrealm. You'll Learn a Lot Here
#
# So, if we want it to find character "r", it would return:
# realm. You'll Learn a Lot Here
#
echo strchr("$output", "D"); ?><br>

I have added commentary to the above examples, you now have a super ninja tool in your toolbox, go make use of it.

Integers

Integers are any natural number, whether positive or negative, e.g 1, 5, 900, -5, -6, 7, etc are all integer numbers

Up until now, we have seen a simple example of using integers with simple operations, now we are going to dive deep a bit on more examples.

Consider we have the following assigned to the below variables:

					

<?php
$var1 = 5;
$var2 = 3;

As you have seen before we can add, multiply, subtract and even divide value of 2 variables, so, to add the 2 variables, you do:

					

<?php echo $var1 + $var2; ?>

# Output is: 8

The above would simply return 8, you can apply the same syntax to substraction, division, and multiplication, so, I don’t need to show you that again.

Here is a bit more advanced example:

					

<?php echo ((2 + 2 + $var1)) * + $var2; ?>

# Output is: 27

The above is a basic math, and the math rules still apply in PHP, so, what happens here is that it would first do operation on 2 + 2 + $var1, which is 9, and it then multiply the result by 3 ($var2), which then gives us 27.

Now, let’s get into math function, here are examples of how it works (I have added explanations on all of ’em):

					

<?php
$var1 = 5;
$var2 = 3;

#
# Example 1: abs(number) (This function is used to return the absolute (positive) value of a number.)
#
# The output of the below is: 3
#
echo abs(0 - $var2);?><br>

<?php
#
# Example 2: pow(base, number) (This function  returns x raised to the power of y, e.g 2^2 = 4.)
#
# The output of the below is: 3125
#
echo pow(5, $var1);?><br>

<?php
#
# Example 3: sqrt(arg: number) (This function multiply a number by itself)
#
# The output of the below is: 5
#
echo sqrt(25);?><br>

<?php
#
# Example 4: rand() (Gives any random number)
#
# The output can be any integer number :)
#
echo rand();?><br>

<?php
#
# Example 5: rand(min, max) (Gives any random number between two numbers)
#
# The output can be any number between 10 and 100 (:
#
echo rand(10, 100);?><br>

If the variable already has an integer value, and you want to basic operation (add, sub, divide, multiply) on it, here are short and superb way, you can do it real quick:

					

<?php echo $var1 += 4; ?><br> # Take the value of $var1 and add it by 4, while also storing it in $var1

<?php echo $var1 *= 4; ?><br> # Take the value of $var1 and multiply it by 4, while also storing it in $var1

<?php echo $var1 /= 2; ?><br> # Take the value of $var1 and divide it by 4, while also storing it in $var1

<?php echo $var1 -= 4; ?><br> # Take the value of $var1 and minus it by 4, while also storing it in $var1

Keep in mind that, whatever you get would be replaced by the last operation, for example, if you have $var1 set to 5, and you did $var1 += 4;, the answer would be the new value of $var1, which in this case would be 9.

Before we go to the next section, let’s look at increment and decrement in PHP, if for example $var1 is 5, and you want to increment it by 1, you can do:

					

<?php echo $var1++; ?>

# The output is: 5

If you do the above, the output is still going to be 5 (I’ll explain why later), but here is the fix:

					

<?php $var1++; 
 echo $var1; ?>

# The output is: 6

The above is called post-increment, it also applies to substraction, which would be $var-- this is called post-decrement.

Isn’t it weird that the first time we tried incrementing the value in the variable, it didn’t work until we had to output it again below the code, before I explain why it works that way, let me introduce you to pre-increment, here is how that works:

					

<?php echo ++$var1; ?>

# The output is: 6

Haha, this gives us 6 right off the bat, now, here is the explanation:

post-increment ($var1++) and the pre-increment(++$var1) are used to increase the value by one while decrement is the opposite of increment; decrease the value by one.

When using a post-increment (e.g i = $var1++), it means first assign the value of ‘$var1’ to ‘i’, then increment x, which is why we have post; after. It won’t get used immediately, only after.

Pre-increment (e.g i = ++$var1) means increment $var1 first and then assign the value of x to y straight away, so, when using pre-increment, it increment or decrement straight away.

Let’s take another example, say you have the following:

If the value of ‘$var1’ is 5 then value of variable ‘i’ will be 5 because old value of ‘x’ is used, remember post means after.

If you have the following:

If the value of ‘$var1’ is 5 then value of variable ‘i’ will be 6 because the value of i gets incremented before using it in a expression.

So, when should you use one of the two?

The answer is simple, use post-increment when you don’t want to increment straight away, and use pre-increment when you want to increment right-way, pre-increment will be faster since it doesn’t make any copy.

Floating Point

If you did an introduction to computer in college, then floating point or any other data type shouldn’t be new to you, for those that didn’t take this in college or people self-learning (the explanation is beyond the scope of this guide) but all you ever need to know about them, is that they are decimal numbers, e.g a number that has a decimal in them followed by a significant digit e.g 88.222727.

So, when dealing with a number that can’t give us an even result, it results in a floating-point number, in most cases, PHP would handle this for you, e.g, when you do 4/5 it gives you:

					

<?php echo 4/5; ?>

# Output is: 0.8

There are a couple of handy functions you can use when doing floating operations, and here are some of them:

					

<?php
$var = 6.4744563;
#
# Example 1: round(number, precison) (This function helps in rounding to a specific decimal place.)
#
# The output of the below is: 6.47
#
# We got 6.47 cos we are rounding it to two decimal place
#
echo round($var, 2);?><br>

<?php
#
# Example 2: ceil(number) (ceiling always round up)
#
# The output of the below is: 7
#
# It doesn't follow the rules of rounding, it just rounds the numbers up
#
echo ceil($var);?><br>

<?php
#
# Example 3: floor(number) (floor always rounds down)
#
# The output of the below is: 6
#
# It doesn't follow the rules of rounding, it just rounds the numbers down
#
echo floor($var);?><br>

Before we conclude this section, there are ways to check if a variable is an integer, a float and even a number. So, if the testing is true, it returns 1 (this is a boolean and stands for true, we would learn more on that in the next section), if false it returns empty, in some programming language, Zero (0) stands for false, this is the same in PHP, but you’ll only get an output of empty, but it would be stored in memory as Zero (0), here are the examples of how it is done:

					

<?php
$int = 3;
$float = 56.8533;
#
# Example 1: is_int(number) (returns 1 if the variable is integer(true), and empty for (false))
#
?>

<?php echo is_int($int); # The output of this is: 1 ?><br>
<?php echo is_int($float); # The output of this is: " " ?><br>

<?php
#
# Example 2: is_float(number) (returns 1 if the variable is float(true), and empty for (false))
#
?>
<?php echo is_float($int); # The output of this is: " " ?><br>
<?php echo is_float($float); # The output of this is: 1 ?><br>

<?php
#
# Example 3: is_numeric(number) (returns 1 if the variable is numeric(true), and empty for (false))
#
# Note: Numeric can be both integer and float
#
?>
<?php echo is_numeric($int); # The output of this is: 1 ?><br>
<?php echo is_numeric($float); # The output of this is: 1 ?><br>

Note: I spent 45 minute trying to debug the reason why the is_numeric keeps giving me false, it turns out I left out the echo command, so, learn from my mistake 🙂

Booleans

We’ve seen an example of boolean, but you might not be aware of it, Boolean is a type that can either be True or False, they can only have one of two values (True or False), please note that the Ture is not the string, “True”, likewise the False is not the string “False”. It’s simply the value True and False and as you’ve seen, they can be used to perform tests on operation.

In our floating-point example above, the result of the is_intor is_floatwas simply True (1) or False (Nothing), the interesting thing about this is that you can simply set a variable True and False, for example:

					
 

<?php
$myVar1 = true; // or you can use capital letter TRUE
$myVar2 = false; // or you can use capital letter FALSE
?>

<?php echo $myVar1; ?><br>
<?php echo $myVar2; ?><br>

The first one would simply return 1, while the second one would return ” ” (nothing).

Just like the rest of the type we’ve seen so far, there is also a function to test if a variable is boolean or not, and as you have guessed, you do that using is_bool

Well, if the result of the variable is a boolean, it is gonna return 1, same 😉

Constant

Constant is the opposite of a variable, they can’t be varied, meaning you can’t change the value once it is set.

It remains constantly set at the same value even when you want to change it at other places in your code, it won’t, they are constant, and they are useful when you want to set, for example, a “Home Directory”, “Path to your image”, “Database Passwords” etc. Those don’t change often, so using a constant is a solid idea.

Constants are written in capital letters without the dollar sign, this is an example of a constant:

<?php

define("PASSWORD", 'epsuu#tL');
echo PASSWORD;

We use a special function define, we provide the name and the value we want to assign to the constant. Also note that we use quotes to surround the constant, but when it is used, we do not use the quote.

Again, you can’t change the value of a Constant nor can you redefine it, but if you desperately want to change it, the only option you have is manually changing it in the place you defined it.

Let’s close this guide by learning “Null and Empty”

Null and Empty

In computer programming, a null is a character denoting nothing, so, let’s set two variables, one would be set to null and the other would be set to empty:

					

<?php

$myVar1 = null;
$myVar2 = "";

Now, if we try ouputing the result of the both value, we would simply get nothing at all:

					




# The above would return nothing

Here is the fun thing, there is a way to test if a variable is null or not, and as you’ve guessed, you can use the function is_null, now let’s see the function is_null in action:

					
 

<?php

$myVar1 = null;
$myVar2 = "";
?>

<?php echo is_null($myVar1); # The output of this is: 1 ?>
<?php echo is_null($myVar2); # The output of this is: " " ?>

The first one returned true, that is pretty obvious as we have it set to null, and the second one return nothing, which might be confusing as the value of the variable is empty, before I explain why we have that result, I want you to keep in mind that if you check the null of a variable that is not set, it is going to return true but with a warning of undefined variable, it kinda makes sense for it to return true as there is nothing in there, but you can avoid the warning totally by setting the variable to null manually.

Back to why the second variable return boolean false – The reason for that is because the variable is actually empty, it isn’t null in the sense that it still has a length, when a variable is empty it has a length of 0 stored in memory (I explained this in the Floating-Point section above).

The following are considered empty: “” (an empty string), NULL, 0 (0 as an integer), 0.0 (0 as a float), “0” (0 as a string), FALSE and even array() (an empty array).

To check if a variable is empty, you can use:

					
 

<?php

$myVar1 = null;
$myVar2 = "";
?>

<?php echo empty($myVar1); # The output of this is: 1 ?>
<?php echo empty($myVar2); # The output of this is: 1 ?>
<?php echo empty($myVar3); # The output of this is: 1 ?>

As you can see they all return 1, even the variable that hasn’t been set ($myVar3) also returns 1 because it is practically empty.

There is another function named isset, it looks if the variable is actually assigned a value, let’s take an example:

					

<?php

$myVar1 = null;
$myVar2 = "";
?>

<?php echo "Null is " . isset($myVar1); # The output of this is: "" ?><br>
<?php echo "Empty is " . isset($myVar2); # The output of this is: 1 ?><br>
<?php echo  "Var3 is " . isset($myVar3); # The output of this is: " " ?><br>

As you can see the variable that we set to empty output True, which is why I said an empty still has zero length in memory, while null doesn’t exist at all in memory.

Use empty when you understand what is empty, and use isset when you trying to check if something is actually set.

This would conclude our guide on Exploring Variables, Data Types, and Operators in PHP. In future guides, I’ll talk about  Arrays, Type Juggling, and more, see ya.

Posted in PHP

Comment policy: Respectful and beneficial comments are welcome with full open hands. However, all comments are manually moderated and those that doesn't relate with what the passage is saying or offensive comments would be deleted. Thanks for understanding!

Leave a Reply

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