PHP Executor

Run and test PHP code directly in the browser.

💡 PHP Basics Guide

1. Declaring Variables and Constants

PHP variables start with $. Use define() or const for constants.

$x = 10;
$pi = 3.14;
$name = "Alice";
$isActive = true;

define("MAX_USERS", 100);
const APP_NAME = "CodeUtility";
2. Conditionals (if / switch)

Use if, elseif, and else for branching, or switch for multiple cases.

$x = 2;
if ($x == 1) {
    echo "One\n";
} elseif ($x == 2) {
    echo "Two\n";
} else {
    echo "Other\n";
}

switch ($x) {
    case 1:
        echo "One\n";
        break;
    case 2:
        echo "Two\n";
        break;
    default:
        echo "Other\n";
}
3. Loops

PHP supports for, while, and foreach loops.

for ($i = 0; $i < 3; $i++) {
    echo $i . "\n";
}

$n = 3;
while ($n > 0) {
    echo $n . "\n";
    $n--;
}
4. Arrays

Arrays hold multiple values. PHP supports indexed and associative arrays.

$nums = array(10, 20, 30);
echo $nums[1];
5. Array Manipulation

Use functions like array_push(), array_pop(), count(), and slicing with array_slice().

$fruits = ["apple", "banana"];
array_push($fruits, "cherry");
array_pop($fruits);
print_r($fruits);

$sliced = array_slice($fruits, 0, 1);
print_r($sliced);
6. Console Input/Output

Use readline() for CLI input and echo/print for output.

$name = readline("Enter your name: ");
echo "Hello, $name\n";
7. Functions

Functions encapsulate reusable logic. Parameters can have default values.

function greet($name = "Guest") {
    return "Hello, $name";
}

echo greet("Alice");
8. Associative Arrays

PHP arrays can act like dictionaries with string keys.

$person = ["name" => "Bob", "age" => 25];
echo $person["name"];
9. Exception Handling

Use try, catch, and throw to handle errors.

try {
    throw new Exception("Something went wrong");
} catch (Exception $e) {
    echo $e->getMessage();
}
10. File I/O

Use functions like fopen(), fwrite(), and fread() for file operations.

$file = fopen("test.txt", "w");
fwrite($file, "Hello File");
fclose($file);

$file = fopen("test.txt", "r");
echo fread($file, filesize("test.txt"));
fclose($file);
11. String Manipulation

Use functions like strlen(), str_replace(), and explode().

$text = "Hello World";
echo strlen($text);
echo str_replace("Hello", "Hi", $text);
print_r(explode(" ", $text));
12. Classes & Objects

Use classes to model real-world objects and reuse logic.

class Person {
  public $name;
  function __construct($name) {
    $this->name = $name;
  }
  function greet() {
    return "Hi, I'm " . $this->name;
  }
}

$p = new Person("Alice");
echo $p->greet();
13. References

In PHP, you can pass variables by reference using &.

function addOne(&$num) {
    $num++;
}

$x = 5;
addOne($x);
echo $x; // 6