PHP Variables Interview Questions and Answers
How to check if a variable is empty in PHP?
Use the empty() function. It returns true when the variable does not exist or has a false-like value, and false otherwise.
<?php
$a = "";
$b = "0";
$c = "Hello";
var_dump(empty($a));
var_dump(empty($b));
var_dump(empty($c));
?>
Output:
bool(true)
bool(true)
bool(false)
These values are all empty: "", 0, 0.0, "0", null, false, [] and an undefined variable. The string “0” is a surprise for many people, so do not use empty() when 0 is a valid value.
Read the full chapter PHP empty() and the comparison isset() vs empty() vs is_null().
How to define a Constant in PHP?
Use the define() function or the const keyword. A constant is like a variable, but its value can not change after it is set. It is used for values that rarely change, like a tax rate or the site name.
<?php
define("TAX_RATE", 18);
const SITE_NAME = "Tutorials Class";
echo SITE_NAME . " tax: " . TAX_RATE . "%";
?>
Output:
Tutorials Class tax: 18%
Do not write the dollar sign ($) before a constant name. By convention names are in capital letters. Read all the rules in PHP Constants, and see the constant() function.
Difference Between Cookies and Session
Both cookies and sessions remember information about a visitor, but they keep it in different places.
| Cookie | Session | |
|---|---|---|
| Stored in | The visitor browser | The server |
| Size limit | About 4 KB | No fixed limit (depends on the server) |
| Visible to the user | Yes, the user can read and change it | No, only the session id is in the browser |
| Lifetime | Until the expiry date you set | Until the browser is closed or the session expires (about 24 minutes of inactivity by default) |
| Best for | Small, harmless data: theme, language, “remember me” token | Private data: login status, user id, shopping cart |
| PHP array | $_COOKIE | $_SESSION |
A session actually uses a cookie too, but only for the session id (called PHPSESSID). PHP uses that id to find the real data on the server. So the private data never goes to the browser.
<?php
// Cookie: stored in the browser
setcookie("theme", "dark", time() + 3600);
// Session: stored on the server
session_start();
$_SESSION["user_id"] = 25;
?>
How can you pass a variable by reference in PHP?
Write an ampersand (&) before the parameter in the function. Then the function works on the original variable, not on a copy.
Normally PHP passes arguments by value. If the function changes the value, the variable outside does not change. With a reference it does.
<?php
function add_line(&$line) {
$line .= " and extra words added.";
}
$sample = "This is a sample line,";
add_line($sample);
echo $sample;
?>
Output:
This is a sample line, and extra words added.
Without the &, the output would be only “This is a sample line,”. Objects are different: PHP passes the handle of an object, so a function can change its properties without any ampersand.
What is the difference between $var and $$var in PHP?
$var is a normal variable. $$var is called a variable variable. PHP takes the value stored in $var and uses it as the name of another variable.
<?php
$var = "city";
$$var = "Delhi"; // same as $city = "Delhi";
echo $var . "<br>";
echo $$var . "<br>";
echo $city;
?>
Output:
city
Delhi
Delhi
Variable variables are hard to read and debug, so use them rarely. In most cases an array is a better choice. See PHP Variables for the basics.
What is the difference between $var++ and $var + 1 in PHP?
$var + 1 only calculates a new value and does not change $var. $var++ is the increment operator, it changes the value of $var by adding 1.
There is one more thing to remember. $var++ (post-increment) returns the old value first and then increases. ++$var (pre-increment) increases first and then returns the new value.
<?php
$a = 5;
$b = $a + 1; // $a is not changed
echo $a . " " . $b . "<br>";
$x = 5;
$y = $x++; // $y gets old value 5, then $x becomes 6
echo $x . " " . $y . "<br>";
$m = 5;
$n = ++$m; // $m becomes 6 first, then $n gets 6
echo $m . " " . $n;
?>
Output:
5 6
6 5
6 6
Which special characters are allowed in PHP variable names?
Only the underscore (_) is allowed as a special character in a PHP variable name. Characters like -, @, # and a space are not allowed.
Here are the full rules:
- A variable name starts with the dollar sign
$. - After the dollar sign, the first character must be a letter or an underscore, not a digit.
- The rest of the name can have letters, digits and underscores.
- Variable names are case-sensitive.
$nameand$Nameare two different variables.
| Variable name | Valid? |
|---|---|
| $name | Yes |
| $_name | Yes |
| $user_name2 | Yes |
| $2name | No, starts with a digit |
| $first-name | No, hyphen is not allowed |
| $first name | No, space is not allowed |
PHP also accepts some non-English letters, but it is better to use only a to z in names. Read more in PHP Variables.
Can we print multiple variables in a single echo statement in PHP?
Yes. You can print many variables in one echo statement. There are three common ways: separate them with a comma, join them with the dot (.) operator, or put them inside double quotes.
<?php
$name = "Robin";
$city = "Delhi";
echo $name, " lives in ", $city, "<br>"; // comma
echo $name . " lives in " . $city . "<br>"; // dot operator
echo "$name lives in $city"; // double quotes
?>
Output:
Robin lives in Delhi
Robin lives in Delhi
Robin lives in Delhi
Variables are replaced by their values only inside double quotes. Single quotes print the text as it is.
How to check the data type of a variable in PHP?
Use var_dump() to see the type and value, gettype() to get the type name, or the is_ functions (like is_int(), is_string(), is_array()) to test a type.
<?php
$a = 343;
$b = "Hello";
$c = 3.14;
$d = [1, 2];
var_dump($a);
echo gettype($b) . "<br>";
var_dump(is_float($c));
echo gettype($d);
?>
Output:
int(343)
string
bool(true)
array
In PHP you do not write the data type when creating a variable, PHP decides it from the value. Learn more in PHP Data Types.
Can a single variable store both digits and characters in PHP?
Yes. If you put digits and characters together inside quotes, PHP stores them as a string. PHP is a loosely typed language, so you do not need to declare the type.
<?php
$variable = "Contact:24/7";
echo $variable . "<br>";
echo gettype($variable) . "<br>";
// The same variable can store another type later
$variable = 24;
echo gettype($variable);
?>
Output:
Contact:24/7
string
integer
Remember that the value in quotes, like "24", is a string and not a number, even if it has only digits. Read PHP Data Types for more.
What is NULL in PHP?
NULL is a special data type in PHP that has only one value, NULL. It means “no value”. NULL is not same as 0, empty string or false.
A variable is NULL in three cases: when you assign NULL to it, when it was never created, or when you remove it with unset().
<?php
$x = "Hello PHP!";
$x = null;
var_dump($x);
var_dump(is_null($x));
var_dump(isset($x));
?>
Output:
NULL
bool(true)
bool(false)
To check for NULL use is_null() or === null. The isset() function returns false for a NULL variable.
What is the use of isset() in PHP?
isset() checks whether a variable is set and is not NULL. It returns true if the variable exists and has a value, otherwise false.
<?php
$name = "Robin";
var_dump(isset($name));
var_dump(isset($age));
?>
Output:
bool(true)
bool(false)
It is mostly used with forms, for example isset($_POST["email"]), to avoid “undefined index” warnings. Read the full chapter PHP isset() function, and learn the difference with empty().
What is the difference between isset(), empty() and is_null() in PHP?
All three check a variable, but in different ways.
- isset() is true when the variable exists and is not NULL.
- empty() is true when the variable does not exist or has a false-like value (0, “”, “0”, NULL, false, []).
- is_null() is true only when the value is NULL (and it gives a warning for an undefined variable).
| Value | isset() | empty() | is_null() |
|---|---|---|---|
| NULL | false | true | true |
| 0 | true | true | false |
| “” (empty string) | true | true | false |
| “Hello” | true | false | false |
| Undefined variable | false | true | true (with warning) |
<?php
$a = null;
$b = 0;
$c = "Hello";
var_dump(isset($a), empty($a), is_null($a));
var_dump(isset($b), empty($b), is_null($b));
var_dump(isset($c), empty($c), is_null($c));
?>
Output:
bool(false)
bool(true)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(false)
Each group of three lines is for one variable: $a, $b and $c. Read the full chapters: isset(), empty() and is_null().
What is type juggling and strict_types in PHP?
Type juggling means PHP converts the data type of a value automatically when needed. For example, the string "10" is treated as a number when you compare or add it with a number.
<?php
var_dump("10" == 10); // string and number, values are same
var_dump("abc" == 0); // false in PHP 8 (it was true in PHP 7)
var_dump(0 == ""); // false in PHP 8 (it was true in PHP 7)
?>
Output:
bool(true)
bool(false)
bool(false)
This automatic change can create bugs. You can ask PHP to be strict with declare(strict_types=1). It must be the first statement of the file, and it affects the function calls made from that file.
<?php
declare(strict_types=1);
function add(int $a, int $b) {
return $a + $b;
}
echo add(2, 3); // 5
// echo add("2", "3"); // TypeError, because strings are not accepted
?>
Output:
5
To be safe, compare with === and use type declarations in functions. See == vs ===.