1 Laravel 11 Basics: PHP in 15 minutes

Master PHP Programming with this comprehensive guide. Perfect for intermediate developers looking to enhance their skills.
Introduction
PHP, or Hypertext Preprocessor, is a powerful server-side scripting language designed for web development but also used as a general-purpose programming language. In this tutorial, we will cover the fundamentals of PHP to help you get started with building dynamic web applications.
Getting Started with PHP
To begin programming in PHP, you need to set up a development environment. The most common way to do this is by installing a local server stack like XAMPP, WAMP, or MAMP, which includes Apache, MySQL, and PHP.
PHP Syntax Basics
A PHP script starts with <?php
and ends with ?>
. Here is a simple example:
<?php
echo "Hello, World!";
?>
Variables
Variables in PHP are represented by a dollar sign followed by the name of the variable. Variable names are case-sensitive.
<?php
$greeting = "Hello, World!";
echo $greeting;
?>
Data Types
PHP supports various data types including strings, integers, floats, booleans, arrays, and objects.
<?php
$string = "Hello, World!";
$int = 123;
$float = 123.45;
$bool = true;
$array = array("foo", "bar", "baz");
?>
Control Structures
PHP offers various control structures, such as if statements, switch statements, and loops (for, while, do-while).
If Statement
<?php
$number = 10;
if ($number > 0) {
echo "$number is positive";
} else {
echo "$number is not positive";
}
?>
For Loop
<?php
for ($i = 0; $i < 10; $i++) {
echo "$i ";
}
?>
Functions
Functions in PHP are declared using the function
keyword. Here is an example:
<?php
function sayHello($name) {
return "Hello, " . $name;
}
echo sayHello("World");
?>
Arrays
Arrays in PHP are used to store multiple values in a single variable. PHP supports both indexed and associative arrays.
Indexed Array
<?php
$colors = array("Red", "Green", "Blue");
echo $colors[0]; // Outputs: Red
?>
Associative Array
<?php
$ages = array("Peter" => 35, "Ben" => 37, "Joe" => 43);
echo $ages['Ben']; // Outputs: 37
?>
Short Array Syntax
PHP allows the use of short array syntax, which is more concise.
<?php
$colors = ["Red", "Green", "Blue"];
echo $colors[0]; // Outputs: Red
?>
Multi-Dimensional Arrays
Multi-dimensional arrays are arrays that contain other arrays. They are useful for storing data in a tabular format.
<?php
$multiArray = [
["John", "Doe", 25],
["Jane", "Smith", 30],
["Sam", "Johnson", 22]
];
echo $multiArray[0][0]; // Outputs: John
echo $multiArray[1][1]; // Outputs: Smith
?>
Array Functions
PHP provides numerous built-in functions for working with arrays.
<?php
$colors = ["Red", "Green", "Blue"];
array_push($colors, "Yellow"); // Adds "Yellow" to the end of the array
print_r($colors); // Outputs: Array ( [0] => Red [1] => Green [2] => Blue [3] => Yellow )
?>
Regular Expressions
Regular expressions are patterns used to match character combinations in strings. PHP provides the preg_match
, preg_match_all
, and preg_replace
functions.
Example of preg_match
<?php
$pattern = "/^foo(.*)/";
$subject = "foobar";
if (preg_match($pattern, $subject, $matches)) {
echo "Match found!";
} else {
echo "No match found.";
}
?>
Object-Oriented Programming (OOP) in PHP
Object-oriented programming (OOP) is a programming paradigm that uses objects and classes. PHP supports OOP with classes, objects, inheritance, polymorphism, interfaces, and traits.
Classes and Objects
<?php
class Car {
public $make;
public $model;
public function __construct($make, $model) {
$this->make = $make;
$this->model = $model;
}
public function getCarInfo() {
return $this->make . " " . $this->model;
}
}
$car = new Car("Toyota", "Corolla");
echo $car->getCarInfo();
?>
Inheritance
<?php
class Vehicle {
public $make;
public $model;
public function __construct($make, $model) {
$this->make = $make;
$this->model = $model;
}
}
class Car extends Vehicle {
public function getCarInfo() {
return $this->make . " " . $this->model;
}
}
$car = new Car("Honda", "Civic");
echo $car->getCarInfo();
?>
Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common super class.
<?php
class Vehicle {
public function startEngine() {
echo "Engine started";
}
}
class Car extends Vehicle {
public function startEngine() {
echo "Car engine started";
}
}
class Motorcycle extends Vehicle {
public function startEngine() {
echo "Motorcycle engine started";
}
}
function startVehicleEngine(Vehicle $vehicle) {
$vehicle->startEngine();
}
$car = new Car();
$motorcycle = new Motorcycle();
startVehicleEngine($car); // Outputs: Car engine started
startVehicleEngine($motorcycle); // Outputs: Motorcycle engine started
?>
Interfaces
Interfaces allow you to specify what methods a class must implement without defining how these methods should be implemented.
<?php
interface VehicleInterface {
public function startEngine();
}
class Car implements VehicleInterface {
public function startEngine() {
echo "Car engine started";
}
}
class Motorcycle implements VehicleInterface {
public function startEngine() {
echo "Motorcycle engine started";
}
}
?>
Traits
Traits are a mechanism for code reuse in single inheritance languages like PHP.
<?php
trait EngineTrait {
public function startEngine() {
echo "Engine started";
}
}
class Car {
use EngineTrait;
}
class Motorcycle {
use EngineTrait;
}
$car = new Car();
$motorcycle = new Motorcycle();
$car->startEngine(); // Outputs: Engine started
$motorcycle->startEngine(); // Outputs: Engine started
?>
Anonymous Functions, Closures, and Arrow Functions
Anonymous Functions
Anonymous functions, also known as closures, are functions without a specified name. They are often used as callback functions.
<?php
$greet = function($name) {
return "Hello, " . $name;
};
echo $greet("World"); // Outputs: Hello, World
?>
Closures
Closures can also capture variables from the surrounding scope.
<?php
$message = "Hello";
$greet = function($name) use ($message) {
return $message . ", " . $name;
};
echo $greet("World"); // Outputs: Hello, World
?>
Arrow Functions
Arrow functions are a shorter syntax for anonymous functions introduced in PHP 7.4. They automatically capture variables from the surrounding scope.
<?php
$message = "Hello";
$greet = fn($name) => $message . ", "
. $name;
echo $greet("World"); // Outputs: Hello, World
?>
Operators
PHP includes a wide range of operators to perform various operations.
Arithmetic Operators
<?php
$a = 10;
$b = 20;
echo $a + $b; // Outputs: 30
echo $a - $b; // Outputs: -10
echo $a * $b; // Outputs: 200
echo $a / $b; // Outputs: 0.5
echo $a % $b; // Outputs: 10
?>
Comparison Operators
<?php
$a = 10;
$b = 20;
var_dump($a == $b); // Outputs: bool(false)
var_dump($a != $b); // Outputs: bool(true)
var_dump($a > $b); // Outputs: bool(false)
var_dump($a < $b); // Outputs: bool(true)
?>
Logical Operators
<?php
$a = true;
$b = false;
var_dump($a && $b); // Outputs: bool(false)
var_dump($a || $b); // Outputs: bool(true)
var_dump(!$a); // Outputs: bool(false)
?>
``>
</Code>
## Database Access and Queries
PHP can interact with databases such as MySQL using extensions like PDO (PHP Data Objects) or MySQLi.
### Connecting to a Database
<Code>
```php
<?php
$dsn = 'mysql:host=localhost;dbname=testdb';
$username = 'root';
$password = '';
try {
$db = new PDO($dsn, $username, $password);
echo "Connected successfully!";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Performing Queries
<?php
$sql = 'SELECT * FROM users';
foreach ($db->query($sql) as $row) {
print $row['name'] . "\t";
print $row['email'] . "\n";
}
?>
Inserting Data
<?php
$name = "John Doe";
$email = "john@example.com";
$sql = 'INSERT INTO users (name, email) VALUES (:name, :email)';
$stmt = $db->prepare($sql);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->execute();
echo "New record created successfully";
?>
Conclusion
In this tutorial, we covered the basics of PHP, including syntax, variables, data types, control structures, functions, arrays (including multi-dimensional arrays), regular expressions, OOP (including inheritance, polymorphism, interfaces, and traits), anonymous functions, closures, arrow functions, operators, and handling database interactions. With these fundamentals, you are well on your way to becoming proficient in PHP programming. For more detailed information, refer to the official PHP documentation.
Discuss Your Project with Us
We're here to help with your web development needs. Schedule a call to discuss your project and how we can assist you.
Let's find the best solutions for your needs.