PHP Fundamentals

Uploaded : 4 months ago Updated : 4 months ago beginner

Take The Quiz

Take The Quiz

The core of PHP logic

You can store values and echo them. Now learn arrays, conditions, loops and functions.

Arrays

<?php
$fruits = ["apple", "pear", "plum"];
$user = ["name" => "Ada", "age" => 30];
echo $fruits[0];      // apple
echo $user["name"];   // Ada

Conditions

<?php
if ($score >= 50) {
  echo "Pass";
} else {
  echo "Try again";
}

=== vs ==

Use === for strict comparison (value AND type). == does loose comparison and can surprise you (e.g. 0 == "a").

Loops

<?php
foreach ($fruits as $fruit) {
  echo $fruit;
}

for ($i = 0; $i < 3; $i++) {
  echo $i;
}

Functions

<?php
function add(int $a, int $b): int {
  return $a + $b;
}
echo add(2, 3); // 5

Useful built-in functions

FunctionWhat it doesExample
count()Items in an arraycount([1,2,3]) → 3
strlen()Length of a stringstrlen("hi") → 2
in_array()Is a value present?in_array(2, [1,2])
implode()Join an array to textimplode(", ", $a)

Beware loose typing

PHP converts types automatically. Use === and type hints (int $a) to avoid silent bugs.

Frequently asked questions

What is an associative array?
An array with named keys ("name" => "Ada") instead of numeric indexes.
Do I need type hints?
Not required, but they make code safer and clearer. Modern PHP encourages them.
What does return do?
It sends a value back to the caller and ends the function.

Time to build

You have arrays, conditions, loops and functions. Build something real.

Continue to PHP in Practice

Comments