PHP Interview Questions – Data Types

1. (Asked in Accenture) What are the different data types supported by PHP?

Answer:
PHP supports eight primary data types:

  • Integer
  • Float (Double)
  • String
  • Boolean
  • Array
  • Object
  • NULL
  • Resource (e.g., database connections, file streams)

2. (Asked in Cognizant) How do you define an integer and a float in PHP? Give an example.

Answer:
Integers are whole numbers without decimals, while floats have decimal points.

Example:

$age = 30;            // integer
$temperature = 37.5;  // float

3. (Asked in Infosys) Explain what a boolean data type is in PHP.

Answer:
A boolean data type represents two possible values: true or false. It is mainly used in conditional statements.

Example:

$is_logged_in = true;

if ($is_logged_in) {
  echo "Welcome!";
} else {
  echo "Please log in.";
}

4. (Asked in TCS) What is the difference between NULL and empty in PHP?

Answer:

  • NULL indicates a variable has no value or is uninitialized.
  • empty() checks if a variable is empty, null, zero, or not set.

Example:

$var1 = NULL;
$var2 = "";

var_dump(empty($var1)); // true
var_dump(empty($var2)); // true

5. (Asked in IBM) What is an array in PHP, and how do you create it?

Answer:
An array is a data type that stores multiple values in a single variable. It can hold values of different types.

Example:

$fruits = array("Apple", "Banana", "Orange");
// or
$fruits = ["Apple", "Banana", "Orange"];

6. (Asked in Google) Explain associative arrays with an example.

Answer:
Associative arrays use named keys rather than numerical indexes.

Example:

$student = [
  "name" => "Amit",
  "age" => 21,
  "course" => "PHP"
];

echo $student["name"]; // Output: Amit

7. (Asked in Amazon) What is type juggling in PHP?

Answer:
Type juggling is PHPโ€™s automatic conversion of data types based on context. PHP automatically converts data types as needed during operations.

Example:

$result = "10" + 5; // string "10" is converted to integer 10
echo $result; // Output: 15

8. (Asked in Wipro) How can you check the data type of a variable in PHP?

Answer:
The gettype() function returns the data type of a variable.

Example:

$var = 25;
echo gettype($var); // Output: integer

9. (Asked in Capgemini) How do you cast a variable from one data type to another in PHP?

Answer:
You can cast a variable by placing the desired data type in parentheses before the variable.

Example:

$num = "100";
$int_num = (int)$num; // cast string to integer

10. (Asked in Microsoft) Explain the resource data type with an example.

Answer:
The resource data type refers to external resources such as file handles or database connections.

Example:

$file = fopen("example.txt", "r"); // file handle resource
var_dump($file); // resource type
fclose($file);