Explain PHP Data Types and Operators
PHP Data Types
A data type specifies the type of value stored in a variable. PHP is loosely typed, so we do not need to explicitly declare the data type of a variable; PHP determines it automatically.
PHP supports 8 main data types.
| Data Type | Meaning | Example |
|---|---|---|
| Integer | Whole numbers | $a = 10; |
| Float (Double) | Numbers with decimal points | $a = 10.5; |
| String | Sequence of characters | $name = "PHP"; |
| Boolean | Represents TRUE or FALSE | $x = true; |
| Array | Stores multiple values | $a = array(10,20,30); |
| Object | Instance of a class | $obj = new Student(); |
| NULL | Represents a variable with no value | $a = NULL; |
| Resource | Reference to an external resource, such as a file or database connection | $file = fopen(...); |
For example, integers represent whole numbers, while floating-point numbers represent real or decimal numbers.
PHP Operators
Operators are symbols used to perform operations on variables and values. The important types of PHP operators are:
Symbols: +, -, *, /, %
Used for mathematical calculations.
Symbols: =, +=, -=, *=, /=, %=
Used to assign or modify values.
Symbols: ==, ===, !=, >, <, >=, <=
Compare two values and return TRUE or FALSE.
Symbols: ++$a, $a++, --$a, $a--
Increase or decrease a variable by 1.
Symbols: .
Joins / concatenates strings, for example: "Hello " . "PHP" → Hello PHP.
Symbols: &&, ||, !
Used to combine or reverse conditions.
Explain Arrays in PHP
An array in PHP is used to store multiple values in a single variable. PHP supports different types of arrays and provides built-in functions for sorting and managing array data.
Types of Arrays in PHP
There are three main types of arrays:
<?php
$names = array("Fabio", "Klevi", "John");
echo $names[0];
?>
Output: Fabio
<?php
$namesAge = array(
"Fabio" => "20",
"Klevi" => "16",
"John" => "43"
);
echo $namesAge["Fabio"];
?>
Output: 20
<?php
$socialNetworks = array(
array("Facebook", "Feb", 21),
array("Twitter", "Dec", 2),
array("Instagram", "Aug", 15)
);
?>
Common Array Functions
PHP provides several built-in functions for working with arrays.
| Function | Purpose |
|---|---|
| sort() | Sorts values in ascending order and creates new numeric indexes. |
| asort() | Sorts by values while preserving keys. |
| ksort() | Sorts an associative array by keys. |
| array_merge() | Combines two or more arrays into one array. |
Explain PHP Tags
PHP tags are used to indicate where PHP code starts and ends in a file. The opening tag tells the server that the code following it is PHP code.
PHP provides the following types of tags:
<?php
echo "Hello";
?>
<?= "Hello"; ?>
<?
echo "Hello";
?>
<script language="php">
echo "Hello";
</script>
<?php ... ?> tag is the recommended method because it is universally supported.
Explain the Filter Function in PHP
PHP provides the Filter Extension to validate and sanitize data. It helps developers handle user input safely without writing complex regular expressions.
Filtering is mainly used for two purposes: validation checks whether data is in the required format, and sanitization removes or converts unwanted or unsafe characters from data.
1. filter_var() Function
The filter_var() function is used to filter a specific variable.
Syntax: filter_var($variable, $filter, $options);
<?php
$email = "abc@gmail.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid Email";
} else {
echo "Invalid Email";
}
?>
Here, FILTER_VALIDATE_EMAIL checks whether the given value has a valid email format.
2. filter_input() Function
The filter_input() function directly gets data from superglobals such as $_GET and $_POST and filters it.
Syntax: filter_input($type, $variable_name, $filter);
For example: $age = filter_input(INPUT_POST, "age", FILTER_VALIDATE_INT);
Common Validation Filters
| Filter | Purpose |
|---|---|
| FILTER_VALIDATE_EMAIL | Checks for a valid email |
| FILTER_VALIDATE_INT | Checks for a valid integer |
| FILTER_VALIDATE_URL | Checks for a valid URL |
Common Sanitization Filters
| Filter | Purpose |
|---|---|
| FILTER_SANITIZE_EMAIL | Removes invalid characters from an email |
| FILTER_SANITIZE_NUMBER_INT | Keeps only digits, + and - |
| FILTER_SANITIZE_SPECIAL_CHARS | Encodes special HTML characters |
Explain Validation in PHP
Validation in PHP is the process of checking whether user input meets the expected format, type, or rules before it is processed or stored. It helps maintain data accuracy, integrity, and application security.
For example, validation can check whether an email address is properly formatted, whether a name has the correct length, whether a number is within a specified range, or whether a required field is empty.
Types of Input Validation
Validation Using PHP Filters
PHP provides built-in validation filters such as FILTER_VALIDATE_EMAIL, FILTER_VALIDATE_INT, and FILTER_VALIDATE_URL.
<?php
$email = "abc@gmail.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid Email";
} else {
echo "Invalid Email";
}
?>
Explain Type Juggling in PHP with Example
Type Juggling in PHP is the automatic conversion of one data type into another when required. PHP is a loosely typed language, so it is not necessary to explicitly declare the datatype of a variable. PHP automatically determines and converts the type when an operation requires it.
Example
<?php
$a = 10; // Integer
$b = "20"; // String
$c = $a + $b; // PHP automatically converts "20" to integer
echo $c;
?>
Output: 30
Here, $a is an integer with value 10 and $b is a string containing "20". When $a + $b is performed, PHP automatically converts the string "20" into an integer, so the addition becomes 10 + 20, producing 30. This automatic conversion of the string into an integer is called Type Juggling.
Type Juggling vs Type Casting
Type juggling should not be confused with type casting:
PHP performs the conversion automatically when required.
The programmer explicitly forces a value into a particular type using a cast operator such as (int), (float), (string) or (bool).
$value = "25";
$number = (int)$value;
Here, (int) explicitly converts the string to an integer.
Explain Variable Scope in PHP with Example
Variable scope in PHP defines where a variable can be accessed in a PHP program. Variables declared inside or outside functions behave differently depending on their scope. The main types are Local Scope and Global Scope.
A variable declared inside a function is called a local variable. It can be accessed only within that function and cannot normally be accessed outside it.
<?php
function test()
{
$num = 100; // Local variable
echo "Inside Function: " . $num;
}
test();
echo "<br>";
echo $num; // Error
?>
Output:
Inside Function: 100
Undefined variable: num
Here, $num is created inside the test() function, so it exists only within that function. Trying to access it outside the function produces an error. Local variables are also destroyed after the function execution ends.
A variable declared outside all functions is called a global variable. It can normally be accessed outside functions. To access it inside a function, PHP provides the global keyword.
<?php
$name = "BCA"; // Global variable
function display()
{
global $name;
echo "Name: " . $name;
}
display();
?>
Output: Name: BCA
Here, $name is declared outside the function. The statement global $name; allows the function to access the global variable.
$GLOBALS array, which can be used to access global variables inside a function.
Summary
| Scope | Where Declared | Where Accessible |
|---|---|---|
| Local | Inside a function | Only inside that function |
| Global | Outside all functions | Outside functions; inside using global or $GLOBALS |
Differentiate Between include and require Statements in PHP
Both include and require are PHP statements used to include the contents of another PHP file into the current script. They are useful for reusing common code such as functions, headers, configuration files, etc.
| Aspect | include | require |
|---|---|---|
| Missing File | Generates a warning; the script generally continues executing. | Generates a fatal error; script execution stops. |
| Suitability | Suitable when the included file is optional. | Suitable when the included file is essential for the application. |
| Use Case | Used when failure to include the file should not stop the entire program. | Used when the program cannot work correctly without the file. |
Example of include
<?php
include "header.php";
echo "Welcome to the website";
?>
If header.php is missing, PHP gives a warning, but the remaining code can continue executing.
Example of require
<?php
require "config.php";
echo "Database application started";
?>
If config.php is missing, execution stops because the required file is essential.
include -> Warning -> Script continues
require -> Fatal error -> Script stops
include for optional files and require for essential files such as configuration or database connection files.
Differentiate Between echo and print Statements in PHP
Both echo and print are used in PHP to display output on the screen.
| Aspect | echo | |
|---|---|---|
| Arguments | Can output multiple strings/values separated by commas. | Accepts only one argument. |
| Return Value | Does not return a value. | Returns the value 1 after successful execution. |
| Speed | Generally considered slightly faster, as it does not return a value. | Slightly slower, as it returns a value. |
| Parentheses | Optional. | Also optional. |
Example using echo
<?php
$name = "Rahul";
$age = 20;
echo "Name: ", $name, " Age: ", $age;
?>
Output: Name: Rahul Age: 20
Example using print
<?php
$name = "Rahul";
print "Name: " . $name;
?>
Output: Name: Rahul
Key Difference: echo can accept multiple arguments and does not return a value, while print accepts one argument and returns 1.
echo is generally preferred when simply displaying output.
Explain Array Operations: sort(), asort(), ksort(), array_merge()
PHP provides several built-in functions for sorting and combining arrays. The important operations are sort(), asort(), ksort(), and array_merge().
Sorts an array in ascending order according to its values. It also re-indexes the array with numeric keys starting from 0.
$numbers = [40, 10, 30, 20];
sort($numbers);
print_r($numbers);
Output:
Array
(
[0] => 10
[1] => 20
[2] => 30
[3] => 40
)
Sorts an array in ascending order according to its values, but preserves the original keys.
$marks = [
"Rahul" => 70,
"Amit" => 90,
"Neha" => 80
];
asort($marks);
print_r($marks);
Output:
Array
(
[Rahul] => 70
[Neha] => 80
[Amit] => 90
)
Here, the values are sorted, but the student names remain associated with their original values.
Sorts an associative array according to its keys in ascending order.
$marks = [
"Neha" => 80,
"Amit" => 90,
"Rahul" => 70
];
ksort($marks);
print_r($marks);
Output:
Array
(
[Amit] => 90
[Neha] => 80
[Rahul] => 70
)
Here, the keys (names) are sorted alphabetically while their corresponding values remain associated with them.
Combines two or more arrays into a single array.
$array1 = ["Apple", "Banana"];
$array2 = ["Mango", "Orange"];
$result = array_merge($array1, $array2);
print_r($result);
Output:
Array
(
[0] => Apple
[1] => Banana
[2] => Mango
[3] => Orange
)
For arrays with numeric keys, the resulting array is re-indexed starting from 0.
Summary
| Function | Operation | Key Behaviour |
|---|---|---|
| sort() | Sorts by values in ascending order | Re-indexes numeric keys |
| asort() | Sorts by values in ascending order | Preserves keys |
| ksort() | Sorts by keys in ascending order | Preserves key-value relationship |
| array_merge() | Combines multiple arrays | Numeric keys are re-indexed |
sort() sorts values and resets keys, asort() sorts values while preserving keys, ksort() sorts by keys, and array_merge() combines arrays.