yttcom.net · Tech · PHP Education
← Back to Guides
Guide 02
PHP Basics
Variables, strings, arrays, loops, and functions. These are the building blocks every PHP file is made of.
Variables — storing a value
A variable is a named container for a piece of data. In PHP, every variable starts with a dollar sign $. You create it by assigning a value with =.
$name = "David"; // text (called a string)
$count = 42; // a number
$price = 12.99; // a decimal number
$active = true; // true or false (boolean)
echo $name; // outputs: David
Analogy: A variable is like a labeled box. You put something in it, stick a label on the outside, and later you can open it by using the label name.
Strings — working with text
A string is just text. Put it in quotes. Use a dot . to join strings together.
$first = "Joshua";
$last = "Tree";
echo $first . " " . $last; // Joshua Tree
// Useful string tools
strlen("hello") // 5 — how long is this string?
strtoupper("hello") // HELLO
trim(" hello ") // "hello" — remove extra spaces
str_replace("a","@","cat") // c@t — swap characters
Arrays — lists of things
An array holds multiple values in one variable. Think of it as a list. You can also use named keys instead of numbers — that is called an associative array.
// Simple list
$travelers = ["David", "Vilma", "Markus", "Ashley"];
echo $travelers[0]; // David (counting starts at 0)
echo $travelers[2]; // Markus
// Named keys (associative array)
$trip = [
"destination" => "Joshua Tree",
"nights" => 2,
"paid" => true
];
echo $trip["destination"]; // Joshua Tree
echo count($travelers); // 4
Analogy: A simple array is a numbered list. An associative array is a form — each field has a label and a value.
if / else — making decisions
PHP can make decisions based on conditions. If the condition is true, run one block of code. Otherwise run the other.
$token = "abc123";
if ($token === "abc123") {
echo "Access granted";
} else {
echo "Unauthorized";
}
// === means EXACTLY equal — same value AND same type
// Don't use == for comparisons involving strings or security
foreach — doing something for each item
When you have an array and want to do something with every item in it, use foreach.
$systems = ["Builder", "Tech", "Health", "Finance"];
foreach ($systems as $system) {
echo $system . "\n";
}
// Outputs:
// Builder
// Tech
// Health
// Finance
// With associative arrays — get both key and value
foreach ($trip as $key => $value) {
echo $key . ": " . $value . "\n";
}
Functions — reusable code blocks
A function is a named block of code you can run anytime by calling its name. You write it once and use it many times. Functions can accept inputs (parameters) and return a result.
function greet($name) {
return "Hello, " . $name . "!";
}
echo greet("David"); // Hello, David!
echo greet("Vilma"); // Hello, Vilma!
// Function with a default value
function greet2($name, $word = "Hello") {
return $word . ", " . $name . "!";
}
echo greet2("Markus", "Hey"); // Hey, Markus!