Variable Scope — PHP Technical Interview Questions & Answers
Variable Scope
Variable Scope
- A PHP variable starts with $ and a letter or underscore. $marks = 72; $name = 'Asha'; No type on the left by default. Types exist at runtime (int, string, array, object, null).
- Names are case-sensitive: $Marks is not $marks. Assignment is = . Compare with == or === (=== also checks type).
- Trap: marks = 72 without $. Trap: == vs = inside if ($marks = 40) which assigns.
Technical Interview Tip: $marks = 72; Names start with $.
Code Examples for Variable Scope
Variable Scope — working example
<?php
// Variable Scope
$scores = [80, 90, 70];
$avg = array_sum($scores) / count($scores);
echo "avg=" . number_format($avg, 1) . "\n";
foreach ($scores as $s) {
if ($s >= 80) echo "high: $s\n";
}Variable Scope: scores array, print avg, then high marks. Say the output.
How to Explain Variable Scope to an Interviewer
How do you create a variable?
$marks = 72; Must start with $