PHP Script Examples with Source Code

PHP (PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML. PHP code is executed on the server-side and the result is sent to the browser as plain HTML.

PHP scripts are processed by a PHP interpreter implemented as a web server module, CGI executable or as a standalone shell on the server.

Some of the key features that make PHP one of the most popular server-side languages include:

  • Open source with vast community support
  • Cross-platform compatibility
  • Ability to connect to various database systems
  • Fast performance
  • Integration with various web servers
  • Extensive collection of predefined functions and syntax
  • Support for various programming paradigms – OOP, procedural, functional etc.

In this article, we will look at some common and useful PHP script examples with source code across different domains. These code snippets and scripts demonstrate PHP’s capabilities and key features for beginners looking to learn through examples.

1. Hello World Example

The Hello World program is the simplest PHP script that outputs a text message ‘Hello World!’. It is used to ensure that the PHP engine is installed and working properly.

// PHP code starts after <?php

// Print text with echo
echo "Hello World!";


This script starts with <?php opening tag which indicates start of PHP code. The echo command is used to output the text which is passed within double quotes. The closing ?> tag indicates end of PHP.

2. Variables and Data Types

Variables are used to store data during execution of a PHP script. PHP supports several data types like integers, floats, strings, booleans, arrays etc.

Here is an example demonstrating some of the data types and variable assignment:


// Integer variable
$num = 10; 

// Float variable
$price = 10.50;

// String variable 
$name = "John";

// Boolean variable
$isPublished = true; 

// Print variables
echo $num; 
echo $price;
echo $name;
echo $isPublished;


The $ symbol is used to declare a variable in PHP. Various data types can be stored in the variables and printed using the echo command.

3. Array in PHP

Arrays are used to store multiple values in a single variable. An array can hold values of same or different data types.

Here is an example to demonstrate arrays in PHP:


// Numeric array
$numbers = [10, 20, 30];

// Print full array

// Access single value
echo $numbers[1]; 

// Associative array 
$user = [
  'name' => 'John',
  'age' => 20, 
  'country' => 'USA'

// Print full array

// Access single value
echo $user['country'];


The square brackets are used to create numeric arrays. Associative arrays use key-value pairs where keys can be strings. The print_r function is used to print the full array. Individual array elements can be accessed using their index or key.

4. Strings in PHP

String functions allow various operations on string variables like concatenation, conversion, search & replace etc.

Here are some common string functions:


// Initialize string 
$str = "Hello World";

// Get length of string
echo strlen($str);

// Search for text 
if(str_contains($str, "Hello")){
  echo "String contains Hello";

// Replace text
echo str_replace("World", "PHP", $str); 

// Convert to uppercase
echo strtoupper($str);


strlen gives the length of the string. Functions like str_contains, str_replace and strtoupper perform search, replace and case conversion respectively.

5. Conditional Statements

Conditional statements allow to perform different actions based on different conditions.

Here is an example of if, elseif and else conditional statements in PHP:


$age = 25;

if($age < 18){
  echo "Not eligible to vote";
elseif($age >= 18 && $age <= 65){
  echo "Eligible to vote";
  echo "Senior citizen";


The condition defined in if is checked first. If false, the elseif conditions are evaluated. The else block is executed if none of the previous conditions are true.

6. Loops in PHP

Loops allow repeated execution of a block of code multiple times. PHP supports different kinds of loops including for, while, do while, foreach etc.

Here is an example demonstrating for and foreach loops:-


// For loop  
for($i=1; $i<=5; $i++){
  echo "Number: " . $i . "<br>";

// Iterating array with foreach
$colors = ["Red", "Green", "Blue"];

foreach($colors as $color){
  echo "Color: " . $color . "<br>"; 


The for loop initializes a counter, checks condition and increments the counter in each iteration.

The foreach loop iterates through array elements without using a counter variable.

PHP Script Examples with Source Code

7. Functions in PHP

Functions allow reuse of code by defining a block of statements once and calling it multiple times.

Here is an example demonstrating user-defined and built-in functions:


// User defined function
function add($num1, $num2){
  return $num1 + $num2;

echo "Sum is: " . add(10, 20);

// Built in function
echo abs(-15); // Returns positive value


The function keyword is used to define a custom function in PHP. Built-in functions like abs can directly be called by name.

8. Dates and Time

Dates and time are common elements in many PHP applications. The date() and time() functions help in working with dates and times.

Here are some examples:


// Current date
echo date("d.m.Y");

// Timestamp
echo time();

// Format date
$dateString = "1980-02-25";
$newDate = date("d-m-Y", strtotime($dateString));
echo $newDate;


date() can format timestamps to readable date strings. strtotime() converts text dates to timestamps. This allows date manipulations.

PHP Script Examples with Source Code
PHP Script Examples with Source Code

9. Include Files

Include allows reuse of common PHP code by including it from other files. Here is an example:


<title>PHP Include Example</title>


  <h1>My Website</h1>
  <p>Some common header content</p>



// Include header 
include 'header.php';


<p>Home page content goes here</p>


The include statement inserts the code from header.php into index.php during execution. This allows reusing header code on multiple pages.

PHP Script Examples with Source Code
PHP Script Examples with Source Code

10. Working with Forms

PHP is often used to collect and process form data from HTML forms before saving it.

Here is an example PHP script to process a simple contact form:


<form method="post" action="process.php">
  Name: <input type="text" name="name"><br>
  Email: <input type="text" name="email"><br>
  Message: <textarea name="message"></textarea> <br>
  <input type="submit" value="Submit">



$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message']; 

// Process form data
// Save to database, send email etc

echo "Name: " . $name . "<br>Email: " . $email . "<br>Message: " . $message;


The form data is available in the $_POST array. It can be processed as needed before sending an HTTP redirect response.

Also Checkout:-

The Rise of Smart Earbuds: Integration with Devices

11. File Handling

PHP provides functions to work with files on the server including read, write, delete, upload etc.

Here is an example to demonstrate reading and writing:


// Write to file
$file = fopen("data.txt","w");
fwrite($file,"This is a simple test\n");

// Read from file
$file = fopen("data.txt","r");
echo fread($file,filesize("data.txt"));


The fopen() function opens a file and fwrite() writes content to it. fread() reads the file content based on file size or length.

12. MySQL Database Access

PHP provides integration with MySQL and other databases using extensions like mysqli, PDO etc.

Here is an example to connect, insert, read and delete MySQL records:


// Connect to MySQL database 
$conn = mysqli_connect("localhost","root","","mydatabase");

// Insert record
$sql = "INSERT INTO users(name, email) VALUES('John','')";
mysqli_query($conn, $sql);
// Read records
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);

while($row = mysqli_fetch_assoc($result)){
  echo $row['name'] . "<br>"; 

// Delete record
$sql = "DELETE FROM users WHERE id=1";  
mysqli_query($conn, $sql);


The mysqli_connect() function initializes database connection which can be used for subsequent queries.

13. Object Oriented PHP

PHP supports object oriented programming which allows defining classes with properties and methods.

Here is an example class with a method:


class User {
  // Properties 
  public $name;
  public $age;
  // Method
  function setDetails($name, $age){
    $this->name = $name;
    $this->age = $age;

// Create object
$user1 = new User();

// Call method  
$user1->setDetails("John", 20);

// Print properties
echo $user1->name . "<br>"; 
echo $user1->age;


The $this variable refers to current class instance. Methods allow interaction with object properties.

Also Read: 5 Steps to Add Watermarks to Images with PHP GD Library

14. JSON in PHP

JSON is a common data format used in web services and Ajax applications. PHP provides JSON encoding and decoding functions.

Here is an example:


// PHP array 
$users = [
     'name' => 'John',
     'age' => 25   

     'name' => 'Mary',
     'age' => 20

// Convert to JSON
$jsonData = json_encode($users);

// Output JSON
echo $jsonData;

// Convert back to PHP array
$decodedArray = json_decode($jsonData, true);



The json_encode() function converts a PHP array to JSON format which can be decoded back using json_decode().

Conclusion on PHP Script Examples with Source Code

PHP is a feature-rich server-side scripting language suitable for developing dynamic and interactive web applications.

This article covered a range of basic to intermediate level PHP script examples demonstrating its capabilities for beginners.

The examples provide a quick reference for syntax, functions and libraries to perform common tasks.

These include strings, arrays, loops, functions, forms, database access and more – which serve as building blocks for any PHP programmer.

Going through these practical scripts and trying them out gives a solid foundation to start building real-world PHP applications.

Common Problems

Problem 1: Reverse a String

Input: "Hello World"
Output: "dlroW olleH"



function reverseString($str) {
  return strrev($str);

echo reverseString("Hello World"); // dlroW olleH


The strrev() function can be used to easily reverse a string in PHP.

Problem 2: FizzBuzz

Print numbers from 1 to 100. For multiples of 3 print "Fizz" instead of the number. For multiples of 5 print "Buzz". For numbers which are multiples of both 3 and 5 print "FizzBuzz".



for($i = 1; $i <= 100; $i++) {
  if($i % 3 == 0 && $i % 5 == 0) {
    echo "FizzBuzz";
  } else if($i % 3 == 0) {
    echo "Fizz";
  } else if($i % 5 == 0) {
    echo "Buzz";
  } else {
    echo $i;


Modulus operator is used to check for multiples of 3 and 5.

Problem 3: Find Duplicates in Array

Input: [1,2,3,4,3,5]
Output: 3



function findDuplicates($arr) {
  $duplicates = [];
  foreach($arr as $val) {
    if(in_array($val, $duplicates)) {
      echo $val; 
    $duplicates[] = $val;



Store elements in a separate array and check before inserting.

Problem 4: Palindrome String

Input: "racecar"
Output: true



function isPalindrome($str) {

  $revStr = strrev($str);

  return $str == $revStr;


echo isPalindrome("racecar");


Reverse string and compare with original.

Problem 5: Prime Numbers

Print prime numbers less than 100.



function isPrime($num) {
  if($num < 2) {
    return false;
  for($i = 2; $i <= sqrt($num); $i++){
    if($num % $i == 0) {
      return false;

  return true;

for($i = 2; $i < 100; $i++) {
  if(isPrime($i)) {
    echo $i . " ";


Check for factors up to square root of the number.

Leave a Comment

All you need to know about Apple’s new iPhone 14 series iPhone 14 with emergency SOS function, Apple Ultra Watch unveiled Apple iPhone 14 Pro and 14 Pro Max arrive with pill notch, Always-On Display, and new cameras Apple iPhone 14 Pro and 14 Pro Max arrive with pill notch, Always-On Display, and new cameras Google Unveils Launch Date of its iPhone 14 Competitors