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
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
- 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
Install and set up
- Install PHP 8.3+ (Windows: windows.php.net or XAMPP; Mac:
brew install php; Ubuntu:sudo apt install php-cli). - Install Composer from getcomposer.org.
- In your project folder:
composer require --dev phpunit/phpunit.
Step 1 — the 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$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
Write PHPUnit tests for format_inr: 12 lakh, a small number, one crore, and a negative amount.
<?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
- Start every file with
declare(strict_types=1);so wrong types fail fast. - Rules file: “PHP 8.3+, strict_types, PDO prepared statements, PHPUnit, PSR-12 style”.
- In
php.inifor development keepdisplay_errors=Onanderror_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.
नमस्कार मित्रांनो. Live chapter मध्ये format_inr आणि InrTest आधीच आले आहे. हा सराव Cedar Quill Press नावाच्या वेगळ्या काल्पनिक दुकानावर आहे. तुम्ही AI कडून formatSku हा PHP helper मागता जो लहान department code आणि sequence number वरून DEPT-000123 शैलीचे SKU बनवतो, रिकाम्या किंवा अवैध department आणि non-positive sequence ला स्पष्ट Exception देतो, आणि प्रत्येक case सिद्ध करतो. या drafting मशीनवर php किंवा phpunit binary नाही, म्हणून आम्ही PHPUnit चालवले नाही. समान cases छोट्या Python behavioral twin ने pytest खाली सिद्ध केले: starter twin मध्ये 10 fail आणि 1 pass, आणि fixed twin मध्ये सर्व 11 पास.
नमस्ते दोस्तों. Live chapter में format_inr और InrTest पहले आ चुके हैं. यह अभ्यास Cedar Quill Press नाम की अलग काल्पनिक दुकान पर है. आप AI से formatSku नाम का PHP helper मांगते हो जो छोटे department code और sequence number से DEPT-000123 शैली का SKU बनाए, खाली या अवैध department और non-positive sequence पर साफ़ Exception दे, और हर case साबित करे. इस drafting मशीन पर php या phpunit binary नहीं है, इसलिए हमने PHPUnit नहीं चलाया. वही cases छोटे Python behavioral twin से pytest के तहत साबित किए: starter twin में 10 fail और 1 pass, और fixed twin में सभी 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.
Ravindra Bagale's Tip – मराठी
Prompt मध्ये exact SKU shape, 2 ते 4 letter rule, six-digit padding आणि Exception message substrings लिहा. Python twin ने आधी सिद्ध केले तरीही तुमच्या मशीनसाठी PHPUnit file जपून ठेवा.
Ravindra Bagale's Tip – हिंदी
Prompt में exact SKU shape, 2 से 4 letter rule, six-digit padding और Exception message substrings लिखो. Python twin से पहले साबित करने पर भी अपनी मशीन के लिए PHPUnit file बचाए रखो।
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
- Create a project folder and open a terminal inside it.
- Optional twin setup: on macOS or Linux run
python3 -m venv .venv. On Windows runpy -3 -m venv .venv. - 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. - 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):
<?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):
<?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.txtWrite 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
- Save the starter PHP file and the PHPUnit file in one folder.
- Ask your AI assistant to fix padding, uppercase, validation, and the Exception substrings the tests search for.
- 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.
- 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
- Problem:
formatSku('pub', 123)returnspub-123. Fix: uppercase the department and zero-pad the sequence to six digits. - 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 substring2 and 4in that message. - Problem:
formatSku('INK', 0)returns a label. Fix: reject every non-positive sequence and include the wordpositivein the error text. - Error: PHPUnit cannot find the class. Fix: require or autoload
SkuFormatter.phpbefore 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.
Name the SKU shape in the prompt
Keep exception substrings stable
Prompt मध्ये SKU shape सांगा
Exception substrings स्थिर ठेवा
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
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.