Skip to main content
LiveCodes supports PHP execution in the browser using Uniter (PHP-to-JavaScript runtime) and php.wasm (full PHP via WebAssembly).

Configuration

Language Name: php (Uniter) or php-wasm (WebAssembly)
File Extensions: .php
Editor: Script editor
Compiler: Uniter runtime or php.wasm
Script Type: text/x-uniter-php

PHP with Uniter

Uniter allows PHP code to run in the browser:
<?php

// Basic output
echo "Hello, World!\n";

// Variables
$name = "Alice";
$age = 30;
echo "Name: $name, Age: $age\n";

// Arrays
$numbers = [1, 2, 3, 4, 5];
print_r($numbers);

// Associative arrays
$user = [
    'name' => 'John Doe',
    'age' => 30,
    'email' => '[email protected]'
];
echo $user['name'] . "\n";

// Loops
foreach ($numbers as $num) {
    echo "Number: $num\n";
}

for ($i = 0; $i < 5; $i++) {
    echo "Iteration: $i\n";
}

Functions

<?php

// Function definition
function greet($name, $greeting = "Hello") {
    return "$greeting, $name!";
}

echo greet("Alice") . "\n";
echo greet("Bob", "Hi") . "\n";

// Type declarations
function add(int $a, int $b): int {
    return $a + $b;
}

echo "Sum: " . add(5, 3) . "\n";

// Variable arguments
function sum(...$numbers) {
    return array_sum($numbers);
}

echo "Total: " . sum(1, 2, 3, 4, 5) . "\n";

// Anonymous functions
$multiply = function($x, $y) {
    return $x * $y;
};

echo "Product: " . $multiply(4, 5) . "\n";

Classes and Objects

<?php

class Person {
    private $name;
    private $age;
    
    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
    
    public function greet() {
        return "Hello, I'm {$this->name}";
    }
    
    public function haveBirthday() {
        $this->age++;
    }
    
    public function getAge() {
        return $this->age;
    }
    
    public function __toString() {
        return "{$this->name} ({$this->age})";
    }
}

$person = new Person("Alice", 25);
echo $person->greet() . "\n";

$person->haveBirthday();
echo "New age: " . $person->getAge() . "\n";
echo $person . "\n";

Inheritance

<?php

class Animal {
    protected $name;
    
    public function __construct($name) {
        $this->name = $name;
    }
    
    public function speak() {
        return "Some sound";
    }
}

class Dog extends Animal {
    public function speak() {
        return "Woof! I'm {$this->name}";
    }
    
    public function fetch() {
        return "{$this->name} is fetching";
    }
}

class Cat extends Animal {
    public function speak() {
        return "Meow! I'm {$this->name}";
    }
}

$dog = new Dog("Buddy");
echo $dog->speak() . "\n";
echo $dog->fetch() . "\n";

$cat = new Cat("Whiskers");
echo $cat->speak() . "\n";

Interfaces and Traits

<?php

interface Drawable {
    public function draw();
}

trait Timestamps {
    private $createdAt;
    
    public function setCreatedAt() {
        $this->createdAt = date('Y-m-d H:i:s');
    }
    
    public function getCreatedAt() {
        return $this->createdAt;
    }
}

class Shape implements Drawable {
    use Timestamps;
    
    private $color;
    
    public function __construct($color) {
        $this->color = $color;
        $this->setCreatedAt();
    }
    
    public function draw() {
        return "Drawing a {$this->color} shape";
    }
}

$shape = new Shape("red");
echo $shape->draw() . "\n";
echo "Created at: " . $shape->getCreatedAt() . "\n";

Array Functions

<?php

$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Map
$squared = array_map(function($n) {
    return $n * $n;
}, $numbers);
print_r($squared);

// Filter
$even = array_filter($numbers, function($n) {
    return $n % 2 === 0;
});
print_r($even);

// Reduce
$sum = array_reduce($numbers, function($carry, $item) {
    return $carry + $item;
}, 0);
echo "Sum: $sum\n";

// Sorting
$fruits = ['banana', 'apple', 'cherry'];
sort($fruits);
print_r($fruits);

// Array operations
array_push($fruits, 'date');
array_pop($fruits);
$first = array_shift($fruits);
array_unshift($fruits, 'apricot');

String Functions

<?php

$text = "Hello, World!";

// Case manipulation
echo strtoupper($text) . "\n";
echo strtolower($text) . "\n";
echo ucfirst($text) . "\n";

// Substring
echo substr($text, 0, 5) . "\n";  // "Hello"
echo substr($text, -6) . "\n";     // "World!"

// Split and join
$words = explode(", ", $text);
print_r($words);
echo implode(" - ", $words) . "\n";

// String search
if (strpos($text, "World") !== false) {
    echo "Found 'World'\n";
}

// Replace
$new_text = str_replace("World", "PHP", $text);
echo $new_text . "\n";

// Trim
$padded = "  hello  ";
echo trim($padded) . "\n";

DOM Manipulation

Uniter allows PHP to interact with the browser DOM:
<?php

// Note: DOM manipulation in Uniter requires JavaScript interop
// Use script tags or custom bindings

echo '<div id="content">Hello from PHP!</div>';
echo '<button onclick="alert(\'Clicked!\')">Click me</button>';

// Generate HTML
function createList($items) {
    $html = '<ul>';
    foreach ($items as $item) {
        $html .= "<li>$item</li>";
    }
    $html .= '</ul>';
    return $html;
}

$fruits = ['Apple', 'Banana', 'Cherry'];
echo createList($fruits);

JSON Handling

<?php

// Encode to JSON
$data = [
    'name' => 'Alice',
    'age' => 25,
    'email' => '[email protected]'
];

$json = json_encode($data);
echo $json . "\n";

// Pretty print
$pretty = json_encode($data, JSON_PRETTY_PRINT);
echo $pretty . "\n";

// Decode JSON
$decoded = json_decode($json, true);
echo $decoded['name'] . "\n";

// Object format
$obj = json_decode($json);
echo $obj->email . "\n";

Example Projects

User Form Handler

<?php

class UserForm {
    private $users = [];
    
    public function addUser($name, $email) {
        $this->users[] = [
            'id' => count($this->users) + 1,
            'name' => $name,
            'email' => $email,
            'created' => date('Y-m-d H:i:s')
        ];
    }
    
    public function getUsers() {
        return $this->users;
    }
    
    public function renderUserList() {
        $html = '<ul>';
        foreach ($this->users as $user) {
            $html .= "<li>{$user['name']} ({$user['email']})</li>";
        }
        $html .= '</ul>';
        return $html;
    }
}

$form = new UserForm();
$form->addUser('Alice', '[email protected]');
$form->addUser('Bob', '[email protected]');

echo $form->renderUserList();

Template System

<?php

class Template {
    private $data = [];
    
    public function set($key, $value) {
        $this->data[$key] = $value;
    }
    
    public function render($template) {
        $output = $template;
        
        foreach ($this->data as $key => $value) {
            $output = str_replace("{{" . $key . "}}", $value, $output);
        }
        
        return $output;
    }
}

$tpl = new Template();
$tpl->set('title', 'Welcome');
$tpl->set('name', 'Alice');
$tpl->set('message', 'Hello from PHP!');

$template = '<h1>{{title}}</h1><p>Hi {{name}}, {{message}}</p>';
echo $tpl->render($template);

Data Processing

<?php

$data = [
    ['name' => 'Alice', 'age' => 25, 'city' => 'New York'],
    ['name' => 'Bob', 'age' => 30, 'city' => 'London'],
    ['name' => 'Charlie', 'age' => 35, 'city' => 'Paris'],
    ['name' => 'David', 'age' => 28, 'city' => 'New York'],
];

// Filter by city
$newYorkUsers = array_filter($data, function($user) {
    return $user['city'] === 'New York';
});

echo "Users in New York:\n";
print_r($newYorkUsers);

// Get names only
$names = array_map(function($user) {
    return $user['name'];
}, $data);

echo "Names: " . implode(', ', $names) . "\n";

// Average age
$ages = array_column($data, 'age');
$avgAge = array_sum($ages) / count($ages);
echo "Average age: $avgAge\n";

// Group by city
$byCity = [];
foreach ($data as $user) {
    $byCity[$user['city']][] = $user['name'];
}
print_r($byCity);

Code Formatting

Automatic formatting with Prettier:
<?php
// Before formatting
function test($a,$b){return $a+$b;}

// After formatting (Ctrl+Shift+F)
function test($a, $b) {
    return $a + $b;
}

PHP.wasm (WebAssembly)

For full PHP support, use php-wasm:
<?php

// Full PHP 8.x support with all extensions
$data = [
    'users' => [
        ['name' => 'Alice', 'age' => 25],
        ['name' => 'Bob', 'age' => 30]
    ]
];

echo json_encode($data, JSON_PRETTY_PRINT);
php.wasm provides full PHP 8.x support but has a larger download size compared to Uniter.

Best Practices

Add type hints for better code:
<?php
function add(int $a, int $b): int {
    return $a + $b;
}
Use try-catch for errors:
<?php
try {
    $result = riskyOperation();
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}
Prefer === over ==:
<?php
// Good
if ($value === 0) { }

// Avoid
if ($value == 0) { }  // May have unexpected results

Limitations

Limited Extensions: Uniter supports core PHP but not all extensions. Database and file system operations are limited.
No Superglobals: $_GET, $_POST, $_SERVER etc. are not available in the same way as server-side PHP.
For full PHP compatibility with all extensions, use php-wasm, though it has a larger initial load.

Python

Similar server-side language

Ruby

Dynamic scripting language

JavaScript

Browser native language

TypeScript

Typed JavaScript

Build docs developers (and LLMs) love