Ravindra BagaleCourses & study guides Track your progress
AI CODING ASSISTANTS · CHAPTER 3 · LANGUAGES

How to Code in PHP Using AI

Use an AI assistant to write a PHP function, run it from the command line, and prove it with PHPUnit tests. Works in VS Code, PhpStorm or any editor.

In short: say the PHP version and strict_types, give exact examples, ask for PHPUnit tests, run vendor/bin/phpunit.

Why PHP with AI

WHY

PHP powers WordPress, Laravel apps and many Indian business websites and portals. A lot of old PHP code is online, so AI often writes old-style PHP. A clear prompt keeps it modern and safe.

What you need

WHAT
  • PHP 8.3 or newer: check with php -v.
  • Composer: PHP's package manager, from getcomposer.org.
  • PHPUnit: the standard PHP test tool: composer require --dev phpunit/phpunit.
  • IDE + assistant: VS Code with Copilot or Claude Code, or PhpStorm with Copilot.

How it flows

1 · Describe the function PHP 8, strict types, examples 2 · AI writes code read every line 3 · php file.php check output 4 · Ask for PHPUnit tests edge cases 5 · vendor/bin/phpunit OK = keep

Install and set up

HOW
  1. Install PHP 8.3+ (Windows: windows.php.net or XAMPP; Mac: brew install php; Ubuntu: sudo apt install php-cli).
  2. Install Composer from getcomposer.org.
  3. In your project folder: composer require --dev phpunit/phpunit.

Step 1 — the prompt

COPY THIS PROMPT

Write a PHP 8 function format_inr(float $amount): string with strict_types that formats money the Indian way (lakh and crore commas), 2 decimals, with the ₹ sign, and a minus sign before ₹ for negatives. Example: 1234567.5 → "₹12,34,567.50". When the file is run from the command line, print that example. Only return the code.

Step 2 — the code (tested here)

inr.php
<?php
// Format a number the Indian way (lakh, crore). Built with an AI assistant, then tested.
declare(strict_types=1);

function format_inr(float $amount): string
{
    $sign = $amount < 0 ? '-' : '';
    $parts = explode('.', number_format(abs($amount), 2, '.', ''));
    $int = $parts[0];
    $last3 = substr($int, -3);
    $rest = substr($int, 0, -3);
    if ($rest !== '' && $rest !== false) {
        $rest = preg_replace('/\B(?=(\d{2})+(?!\d))/', ',', $rest);
        $last3 = $rest . ',' . $last3;
    }
    return $sign . '₹' . $last3 . '.' . $parts[1];
}

if (PHP_SAPI === 'cli' && realpath($_SERVER['argv'][0] ?? '') === __FILE__) {
    echo format_inr(1234567.5), PHP_EOL;   // ₹12,34,567.50
}
php inr.php
# -> ₹12,34,567.50
Real catch while writing this: the first AI version used $argv[0] to check if the file was run directly. When PHPUnit loaded the file, $argv was not defined there, and PHP printed warnings. The fix: $_SERVER['argv'][0] ?? ''. The tests found it, not our eyes.

Step 3 — ask for PHPUnit tests, then run them

FOLLOW-UP PROMPT

Write PHPUnit tests for format_inr: 12 lakh, a small number, one crore, and a negative amount.

InrTest.php
<?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
require_once __DIR__ . '/inr.php';

final class InrTest extends TestCase
{
    public function testLakh(): void  { $this->assertSame('₹12,34,567.50', format_inr(1234567.5)); }
    public function testSmall(): void { $this->assertSame('₹999.00', format_inr(999)); }
    public function testCrore(): void { $this->assertSame('₹1,00,00,000.00', format_inr(10000000)); }
    public function testNegative(): void { $this->assertSame('-₹1,500.00', format_inr(-1500)); }
}
vendor/bin/phpunit InrTest.php
# -> OK (4 tests, 4 assertions)

Settings and config

  1. Start every file with declare(strict_types=1); so wrong types fail fast.
  2. Rules file: “PHP 8.3+, strict_types, PDO prepared statements, PHPUnit, PSR-12 style”.
  3. In php.ini for development keep display_errors=On and error_reporting=E_ALL, so warnings like the one above show up.

Watch out (common AI mistakes in PHP)

  • SQL injection — never build SQL by joining strings; ask for PDO prepared statements.
  • Old mysql_* functions — removed in PHP 7; use PDO or mysqli.
  • No output escaping — use htmlspecialchars() when printing user input.
  • Made-up Composer packages — check on packagist.org.

Try this yourself: ask AI for a PHP SKU formatter, then prove the cases

Hello friends. The live chapter already walked through format_inr with InrTest. This practice is a different fictional shop called Cedar Quill Press. You ask an AI for a PHP helper formatSku that builds DEPT-000123 style SKUs from a short department code and a sequence number, rejects empty or invalid departments and non-positive sequences with clear Exception messages, and proves every case. On this drafting machine there is no php or phpunit binary, so we did not run PHPUnit. We proved the same cases with a tiny Python behavioral twin under pytest: the starter twin failed 10 tests and passed 1, and the fixed twin passed all 11.

Ravindra Bagale's Tip

Put the exact SKU shape, the 2 to 4 letter rule, the six-digit padding, and the Exception message substrings in your prompt. Keep the PHPUnit file for your machine even when you first prove the same cases with the Python twin.

Practice label: Cedar Quill Press, every department code and every sequence number here is fictional teaching data. It is not a real publisher or inventory system. Passing these tests proves only the listed cases.
Environment (tested): on 6 November 2026 this box had no php or phpunit, and none was installed. The same SKU cases were proved with a Python twin under Python 3.13.5 and pytest 9.1.1. Starter twin: 10 failed, 1 passed. Fixed twin: 11 passed. PHPUnit was not run. The SkuFormatterTest.php file is still the student-facing PHP test source.

Your task: start from the buggy SkuFormatter.php that concatenates a short label with three-digit padding but skips validation and uppercase. Ask an AI to trim and uppercase the department, accept only 2 to 4 ASCII letters, require a positive sequence, zero-pad to six digits, throw InvalidArgumentException with the substrings the tests search for, and keep the PHPUnit file for your machine. On machines without PHP yet, you may also use the Python twin.

Setup

HOW
  1. Create a project folder and open a terminal inside it.
  2. Optional twin setup: on macOS or Linux run python3 -m venv .venv. On Windows run py -3 -m venv .venv.
  3. Activate it: on macOS or Linux run source .venv/bin/activate. In Windows Command Prompt run .venv\Scripts\activate.bat, and in Windows PowerShell run .venv\Scripts\Activate.ps1.
  4. Install pytest inside the virtual environment: python -m pip install pytest.

Extra for PHP on your machine: install PHP 8.1 or newer with PHPUnit, confirm php --version, and run the PHPUnit file. This drafting box did not have PHP and did not install one.

Starter SkuFormatter.php (wrong padding, skips validation):

SkuFormatter.php
<?php
// Cedar Quill Press SKU helper (fictional teaching shop — not a real publisher).
// Starter: builds a short label but skips validation and wrong padding.
declare(strict_types=1);

final class SkuFormatter
{
    public static function formatSku(string $dept, int $seq): string
    {
        // Starter bugs: no validation; no uppercase; only 3-digit padding.
        return $dept . '-' . str_pad((string) $seq, 3, '0', STR_PAD_LEFT);
    }
}

PHPUnit-style tests SkuFormatterTest.php (for your machine):

SkuFormatterTest.php
<?php
declare(strict_types=1);

use PHPUnit\Framework\TestCase;

final class SkuFormatterTest extends TestCase
{
    public function testPubOneHundredTwentyThree(): void
    {
        $this->assertSame('PUB-000123', SkuFormatter::formatSku('pub', 123));
    }

    public function testInkOne(): void
    {
        $this->assertSame('INK-000001', SkuFormatter::formatSku('ink', 1));
    }

    public function testArtNineHundredNinetyNineThousand(): void
    {
        $this->assertSame('ART-999999', SkuFormatter::formatSku('ART', 999999));
    }

    public function testAbFive(): void
    {
        $this->assertSame('AB-000005', SkuFormatter::formatSku('ab', 5));
    }

    public function testTrimAndUppercase(): void
    {
        $this->assertSame('INK-000042', SkuFormatter::formatSku('  ink  ', 42));
    }

    public function testRejectsEmptyDept(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessageMatches('/dept/');
        SkuFormatter::formatSku('', 1);
    }

    public function testRejectsOneLetterDept(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessageMatches('/2 and 4/');
        SkuFormatter::formatSku('X', 1);
    }

    public function testRejectsFiveLetterDept(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessageMatches('/2 and 4/');
        SkuFormatter::formatSku('TOOLS', 1);
    }

    public function testRejectsDigitsInDept(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessageMatches('/letters/');
        SkuFormatter::formatSku('A1', 1);
    }

    public function testRejectsZeroSeq(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessageMatches('/positive/');
        SkuFormatter::formatSku('INK', 0);
    }

    public function testRejectsNegativeSeq(): void
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessageMatches('/positive/');
        SkuFormatter::formatSku('INK', -3);
    }
}

Python twin starter (optional local proof without PHP):

sku_formatter.py
"""Behavioral twin of Cedar Quill Press SkuFormatter::formatSku (starter — buggy)."""


def format_sku(dept: str, seq: int) -> str:
    # Starter bugs: no validation; no uppercase/trim; only 3-digit padding.
    return f"{dept}-{seq:03d}"

Suggested AI ask (copy and adapt):

php-prompt.txt
Write a PHP 8.1 final class SkuFormatter with public static function formatSku(string $dept, int $seq): string for fictional Cedar Quill Press. Trim and uppercase dept. Accept only 2 to 4 ASCII letters A-Z. Reject empty, too-short, too-long, or non-letter dept with InvalidArgumentException messages containing dept, and for length cases also containing 2 and 4, and for non-letter cases also containing letters. Reject seq <= 0 with an exception mentioning positive. Return "{DEPT}-{seq zero-padded to 6 digits}" such as PUB-000123. Add PHPUnit tests covering the happy paths and the rejection cases.

HOW to finish

HOW
  1. Save the starter PHP file and the PHPUnit file in one folder.
  2. Ask your AI assistant to fix padding, uppercase, validation, and the Exception substrings the tests search for.
  3. On a machine with PHPUnit run the PHPUnit file. On this drafting box we used the Python twin instead: starter showed 10 failed and 1 passed.
  4. Run again after the fix. Expect 11 passed on the twin (or the matching PHPUnit count on your machine).

Real pytest twin output after the fixed twin:

pytest-after.txt
...........                                                              [100%]
11 passed in 0.01s
Optional completed SkuFormatter.php (try it yourself first)

Your AI assistant may reorder the checks. Any version is fine if the PHPUnit cases (or the Python twin) all pass.

SkuFormatter.php
<?php
declare(strict_types=1);

final class SkuFormatter
{
    public static function formatSku(string $dept, int $seq): string
    {
        $dept = strtoupper(trim($dept));
        if ($dept === '' || !preg_match('/^[A-Z]{2,4}$/', $dept)) {
            throw new InvalidArgumentException(
                'dept must be 2 and 4 letters (A-Z only after trim and uppercase)'
            );
        }
        if ($seq <= 0) {
            throw new InvalidArgumentException('seq must be positive');
        }
        return $dept . '-' . str_pad((string) $seq, 6, '0', STR_PAD_LEFT);
    }
}

Troubleshooting

HOW
  1. Problem: formatSku('pub', 123) returns pub-123. Fix: uppercase the department and zero-pad the sequence to six digits.
  2. Problem: formatSku('TOOLS', 1) returns a label instead of an exception. Fix: reject every department that is not exactly 2 to 4 letters, and put the substring 2 and 4 in that message.
  3. Problem: formatSku('INK', 0) returns a label. Fix: reject every non-positive sequence and include the word positive in the error text.
  4. Error: PHPUnit cannot find the class. Fix: require or autoload SkuFormatter.php before the test class runs.

Practice cards: English and spoken Marathi

Each card below explains one idea on its own, so you can save or revise a single card without reading the whole chapter.

PRACTICE CARDAI Coding

Name the SKU shape in the prompt

Ask for uppercase 2 to 4 letter departments and six-digit zero padding such as PUB-000123.
Run the tests and read which happy paths or rejection cases still fail.
Ravindra Bagale · ravindrabagale.com/ai-coding
PRACTICE CARDAI Coding

Keep exception substrings stable

Tests search for dept, 2 and 4, letters, and positive inside the exception text.
Ask the AI to keep those words even if it rewrites the sentence.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Prompt मध्ये SKU shape सांगा

Uppercase 2 ते 4 letter departments आणि six-digit zero padding जसे PUB-000123 मागा.
Tests चालवा आणि अजून fail होणारे happy paths किंवा rejection cases वाचा.
Ravindra Bagale · ravindrabagale.com/ai-coding
सराव कार्डमराठी

Exception substrings स्थिर ठेवा

Tests exception text मध्ये dept, 2 and 4, letters आणि positive शोधतात.
AI वाक्य बदलले तरीही ती शब्द ठेवायला सांगा.
Ravindra Bagale · ravindrabagale.com/ai-coding

Quick quiz

1. Which tool runs PHP unit tests?

PHPUnit (vendor/bin/phpunit).

2. What does format_inr(1234567.5) return?

₹12,34,567.50.

3. How do you stop SQL injection in PHP?

Use PDO prepared statements, never string-joined SQL.

4. What bug did the tests catch in this chapter?

Using $argv when the file was loaded by PHPUnit caused warnings.

Save tokens and money

SMART AI USE

Paste one function, not the vendor/ folder. Turn on full error reporting locally so PHP tells you the problem for free, then send the AI only that warning line.

Save these cards

INTERVIEW CARDAI Coding

How do you use AI safely for PHP?

PHP 8 + strict_types + examples in the prompt.
PDO prepared statements; prove with PHPUnit.
Ravindra Bagale · ravindrabagale.com/ai-coding
COMPARISON CARDAI Coding

Old PHP vs modern PHP

Old: mysql_*, no types, string SQL.
Modern: PDO, strict_types, typed functions, PHPUnit.
Ravindra Bagale · ravindrabagale.com/ai-coding
REVISION CARDAI Coding

PHP with AI in 3

strict_types on.
Indian format: lakh/crore commas.
phpunit OK = proof.
Ravindra Bagale · ravindrabagale.com/ai-coding