1. (Asked in Infosys) What are operators in PHP? Mention their types.
Answer:
Operators are symbols used to perform operations on variables and values. PHP supports several operator types:
2. (Asked in TCS) Explain arithmetic operators with an example.
Answer:
Arithmetic operators are used to perform mathematical operations.
Example:
$a = 10;
$b = 5;
echo $a + $b; // 15 (Addition)
echo $a - $b; // 5 (Subtraction)
echo $a * $b; // 50 (Multiplication)
echo $a / $b; // 2 (Division)
echo $a % $b; // 0 (Modulus - remainder)
3. (Asked in Cognizant) What is the difference between the ‘==’ and ‘===’ operators in PHP?
Answer:
==
(Equal) checks if two values are equal, ignoring data type.===
(Identical) checks if two values are equal, considering both value and data type.Example:
$a = "5";
$b = 5;
var_dump($a == $b); // true
var_dump($a === $b); // false
4. (Asked in Google) How does the assignment operator (=
) work in PHP?
Answer:
The assignment operator assigns a value to a variable.
Example:
$name = "Rahul"; // Assigns "Rahul" to $name
5. (Asked in Accenture) Explain increment and decrement operators with examples.
Answer:
These operators increase or decrease a variable’s value by 1.
Example:
$x = 5;
echo ++$x; // Output: 6 (pre-increment)
$y = 5;
echo $y++; // Output: 5, then $y becomes 6 (post-increment)
6. (Asked in Amazon) What are logical operators in PHP? Give an example.
Answer:
Logical operators combine conditional statements (&&
, ||
, !
).
Example:
$a = true;
$b = false;
if ($a && !$b) {
echo "Condition met"; // This line executes
}
7. (Asked in IBM) What is a string operator in PHP?
Answer:
The string operator (.
) concatenates (joins) two or more strings.
Example:
$first_name = "Amit";
$last_name = "Sharma";
echo $first_name . " " . $last_name; // Output: Amit Sharma
8. (Asked in Capgemini) Explain array operators in PHP with an example.
Answer:
Array operators are used to combine or compare arrays.
Example:
$arr1 = ["a" => 1, "b" => 2];
$arr2 = ["c" => 3, "d" => 4];
$combined = $arr1 + $arr2; // Union of arrays
print_r($combined);
// Output: Array ( [a] => 1 [b] => 2 [c] => 3 [d] => 4 )
9. (Asked in Facebook) What is the use of the spaceship operator (<=>
) in PHP?
Answer:
The spaceship operator (<=>
) compares two values and returns:
0
if both values are equal.1
if the left side is greater.-1
if the right side is greater.Example:
echo 5 <=> 5; // Output: 0
echo 7 <=> 5; // Output: 1
echo 3 <=> 5; // Output: -1
10. (Asked in Microsoft) What is operator precedence in PHP? Why is it important?
Answer:
Operator precedence determines the order in which PHP evaluates expressions. Understanding precedence ensures correct and expected results.
Example:
echo 2 + 3 * 4; // Output: 14, multiplication happens first (3*4=12, then +2)
echo (2 + 3) * 4; // Output: 20, parentheses first (2+3=5, then *4)