PHP · STEP 1 · INTRO

PHP · Intro to the language

PHP 8.5 (any 8.3+ works): variables, input, conditionals, loops, arrays, associative arrays and functions — each shown first in the JavaScript you know, then in PHP.

Step 1 of 5Laravel© Arthur Bernier Jrrewritten · verified15 code blocks574 words

What you will learn#

  • Creating Variables in a New Language
  • Conditionals in a New Language
  • Looping in a New Language
  • Collections in a New Language
  • Writing Functions in a New Language

Getting Started#

Install PHP from php.net/downloads — 8.5 is current; 8.3+ runs this page and Laravel 13 — or, on macOS and Windows, Laravel Herd, which bundles PHP, Composer and the Laravel installer. Then start PHP's interactive shell:

SH
php --versionphp -a

Type PHP at the php > prompt, exit to leave; php hello.php runs a file. A PHP file starts with <?php; in a file that is only PHP you leave the closing ?> off.

Creating Variables#

How we did it in Javascript

JS
// We create constant variables with the const keywordconst myConstant = 5// We create re-assignable variables with the let keywordlet myVariable = "Hello World" // We print variables to the console using console.logconsole.log(myConstant)console.log(myVariable)

How we do this in PHP

PHP
<?php// const creates a constant; the convention is ALL_CAPS and no $ (define() also works)const MY_CONSTANT = 5;// Every variable starts with a $ and is re-assignable; statements MUST end with a semicolon$myVariable = "Hello World"; // echo prints; "\n" (or PHP_EOL) adds the line break; dot . concatenates stringsecho MY_CONSTANT . "\n";echo $myVariable . "\n";

echo is a language construct, not a function, so parentheses around it are optional; print_r() and var_dump() print arrays and objects.

Receiving Input#

In the browser, input comes from forms or prompt. In Node, it comes from the readline module:

JS
// Node: ask a question in the terminal and wait for the answerimport readline from "node:readline/promises"import { stdin as input, stdout as output } from "node:process" const rl = readline.createInterface({ input, output })const name = await rl.question("Who are you? ")console.log(`Hey there ${name}!`)rl.close()

How would we do that in PHP?

PHP
<?php// readline() prints the prompt, waits for a line and returns it as a string$userInput = readline("Who are you? "); // Variables interpolate inside double-quoted strings (not single-quoted ones)echo "Hey there $userInput\n";

readline() always returns a string; cast when you need a number: (int) readline("Age? ").

Conditionals#

If statements in Javascript

JS
const num = 5 if (num > 3){    console.log("num is greater than 3")} else if (num > 1){    console.log("num is greater than 1")} else {    console.log("num is 1 or less")}

If statements in PHP

PHP
<?php$num = 5; // Same shape as JavaScript; elseif is one word in PHP (else if also parses)if ($num > 3) {    echo "num is greater than 3\n";} elseif ($num > 1) {    echo "num is greater than 1\n";} else {    echo "num is 1 or less\n";}

The operators carry over (==, ===, !=, !==, &&, ||, !), and as in JavaScript == coerces, so prefer ===. PHP 8 also has match, a switch that compares with === and returns a value — the OOP page uses it.

While Loops#

In Javascript

JS
let counter = 0 //This will loop 10 timeswhile(counter < 10){    console.log(counter)    counter += 1}

In PHP

PHP
<?php$counter = 0; // This will loop 10 times (++ and += both exist)while ($counter < 10) {    echo $counter . "\n";    $counter += 1;}

PHP's for loop is JavaScript's (for ($i = 0; $i < 10; $i++)); the one you'll use most, foreach, is in Collections below.

10 Minute Exercise#

Write the code to do the following:

  • Loop 10 times starting the counter at 0
  • On each loop if the counter is even print "it's even"
  • If odd, print "meow" if the number is divisible by 3
  • Otherwise print nothing

Collections#

In Javascript we have arrays and objects

JS
const myArray = [1,2,3] console.log(myArray) //logging the entire arrayconsole.log(myArray[0]) // logging an individual item const myObject = {    cheese: "gouda",    bread: "rye"} console.log(myObject) //logging the entire objectconsole.log(myObject.cheese) // logging a property using dot notationconsole.log(myObject["bread"]) // logging a property using square bracket notation

In PHP we have arrays and associative arrays

PHP
<?php$myArray = [1, 2, 3];print_r($myArray);         // printing the whole arrayecho $myArray[0] . "\n";   // printing an individual item (don't forget the $) $myAssociative = ["cheese" => "gouda", "bread" => "rye"];print_r($myAssociative);               // printing the whole associative arrayecho $myAssociative["cheese"] . "\n";  // one value (?? supplies a default for a missing key) // foreach walks values, or keys and valuesforeach ($myArray as $item) {    echo $item . "\n";}foreach ($myAssociative as $key => $value) {    echo "$key: $value\n";}

One type does both jobs: a PHP array is an ordered map with integer or string keys, and there is no dot access — square brackets only.

10 Minute Exercise#

Look up PHP's array functions and apply them to the following list.

PHP
[1,2,3,4,5,6,7,8,9,10]
  • How to find an array's length (count)
  • How to loop over an array (foreach, array_map)
  • How to add and remove items from an array ($arr[] = 11, array_push, array_pop, unset)

Functions#

in Javascript

JS
const addNums = (x, y) => {    return x + y} console.log(addNums(5,5))

In PHP

PHP
<?php// snake_case or camelCase both appear in the wild; Laravel code uses camelCasefunction addNums(int $x, int $y): int{    return $x + $y;} echo addNums(5, 5) . "\n";

Types are optional but current PHP code writes them. Defaults work as in JavaScript, named arguments are a bonus, and fn is the arrow function:

PHP
<?phpfunction greet(string $name, string $greeting = "Hello"): string{    return "$greeting, $name!";} echo greet("Arthur") . "\n";                      // Hello, Arthur!echo greet("Arthur", greeting: "Welcome") . "\n"; // Welcome, Arthur! // Arrow functions: one expression, and they can see the variables around them$double = fn(int $n): int => $n * 2;echo $double(21) . "\n"; // 42

10 minute exercise#

Write the following functions

  • subNums that takes two arguments and returns their difference
  • sayHello that takes a name as an argument and says hello to that name
  • sayHelloAdv that takes an associative array with a name and age key and prints "hello {name}, how does it feel to be {age} years old"
  • looper takes one array as an argument, loops over the array and prints each item individually

Resources to Learn More#


See also