Hey!! Welcome to our Online PHP Compiler | Free Online Compiler For PHP. You can write PHP code online in this compiler and instantly see the output of the PHP code.

You can enjoy writing PHP code here without installing a compiler on your computer and you can also download the PHP program file by clicking on the three dots at the top-right corner of the editor where you will see the download option.

Introduction and History of PHP:

  • PHP (Hypertext Preprocessor) is an open-source, server-side scripting language
  • Created in 1994 by Rasmus Lerdorf
  • Popular for web development
  • Dynamically generates HTML, processes form data, manages databases, creates dynamic web pages
  • Often used with other technologies like HTML, CSS, and JavaScript
  • Can run on most web servers and compatible with a wide range of operating systems
  • Versatile choice for web development.

PHP syntax and variables:

  • PHP code is embedded in HTML files and interpreted by the server
  • Example of a PHP code block:
  <?php
  // PHP code goes here
  ?>
  • Variables start with a $ sign and use the assignment operator (=) to assign a value
  • Example of assigning a value to a variable:
  <?php
  $name = "John Doe";
  ?>
  • Variable names are case-sensitive and must start with a letter or underscore
  • Example of a valid variable name:
  $first_name
  • PHP supports multiple data types such as strings, integers, floats, arrays, and objects
  • Example of different data types:
  <?php
  $name = "John Doe";
  $age = 30;
  $is_student = false;
  $subjects = array("math", "history", "science");
  ?>
  • Concatenation of strings is done using the concatenation operator (.)
  • Example of concatenating two strings:
  <?php
  $first_name = "John";
  $last_name = "Doe";
  $full_name = $first_name . " " . $last_name;
  ?>
  • Echo and print statements are used to output data to the browser
  • Example of using echo statement to output a string:
  <?php
  echo "Hello World!";
  ?>
  • The echo statement can output multiple values separated by commas
  • Example of using echo statement to output multiple values:
  <?php
  echo "My name is", $name, "and I am", $age, "years old.";
  ?>
  • The PHP syntax follows a similar pattern to C-style languages, with statements ending in a semicolon.

PHP Data Types:

  • PHP supports several data types: String, Integer, Float, Boolean, Array, Object, NULL
  • Example of different data types:
  <?php
  $name = "John Doe"; // String
  $age = 30; // Integer
  $gpa = 3.5; // Float
  $is_student = false; // Boolean
  $subjects = array("math", "history", "science"); // Array
  $person = new stdClass(); // Object
  $nothing = null; // NULL
  ?>
  • Strings are sequences of characters, enclosed in quotes
  • Example of a string:
  <?php
  $name = "John Doe";
  ?>
  • Integers are whole numbers
  • Example of an integer:
  <?php
  $age = 30;
  ?>
  • Floats are numbers with decimal points
  • Example of a float:
  <?php
  $gpa = 3.5;
  ?>
  • Booleans are either true or false
  • Example of a boolean:
  <?php
  $is_student = false;
  ?>
  • Arrays are ordered collections of values
  • Example of an array:
  <?php
  $subjects = array("math", "history", "science");
  ?>
  • Objects are instances of user-defined classes
  • Example of an object:
  <?php
  $person = new stdClass();
  ?>
  • NULL is a special data type representing absence of a value
  • Example of NULL:
  <?php
  $nothing = null;
  ?>

PHP Operators:

  • PHP supports several types of operators: Arithmetic, Assignment, Comparison, Logical, String, Array
  • Example of different types of operators:
  <?php
  $a = 10;
  $b = 20;

  // Arithmetic Operators
  $sum = $a + $b; // 30
  $diff = $b - $a; // 10
  $product = $a * $b; // 200
  $quotient = $b / $a; // 2
  $modulus = $b % $a; // 0

  // Assignment Operators
  $c = $a; // 10
  $c += $b; // 30
  $c -= $a; // 20
  $c *= $b; // 400
  $c /= $a; // 40

  // Comparison Operators
  $is_equal = $a == $b; // false
  $is_not_equal = $a != $b; // true
  $is_greater = $b > $a; // true
  $is_less = $a < $b; // true
  $is_greater_or_equal = $b >= $a; // true
  $is_less_or_equal = $a <= $b; // true

  // Logical Operators
  $result = ($a < $b) && ($b > 0); // true
  $result = ($a < $b) || ($b < 0); // true
  $result = !($a < $b); // false

  // String Operators
  $name = "John" . " " . "Doe"; // John Doe

  // Array Operators
  $subjects = array("math", "history");
  $all_subjects = array_merge($subjects, array("science")); // array("math", "history", "science")
  ?>

PHP Conditional Statements:

  • PHP supports several conditional statements: if, if-else, if-elseif-else, switch
  • Example of different conditional statements:
  <?php
  $age = 25;

  // If Statement
  if ($age >= 21) {
    echo "Eligible to buy alcohol";
  }

  // If-Else Statement
  if ($age >= 21) {
    echo "Eligible to buy alcohol";
  } else {
    echo "Not eligible to buy alcohol";
  }

  // If-Elseif-Else Statement
  if ($age >= 21) {
    echo "Eligible to buy alcohol";
  } elseif ($age >= 18) {
    echo "Eligible to buy tobacco";
  } else {
    echo "Not eligible to buy anything";
  }

  // Switch Statement
  switch ($age) {
    case 21:
      echo "Eligible to buy alcohol";
      break;
    case 18:
      echo "Eligible to buy tobacco";
      break;
    default:
      echo "Not eligible to buy anything";
      break;
  }
  ?>

PHP Loops:

  • PHP supports several loop statements: for, while, do-while, foreach
  • Example of different loop statements:
  <?php
  // For Loop
  for ($i = 0; $i < 5; $i++) {
    echo $i . " "; // 0 1 2 3 4
  }

  // While Loop
  $j = 0;
  while ($j < 5) {
    echo $j . " "; // 0 1 2 3 4
    $j++;
  }

  // Do-While Loop
  $k = 0;
  do {
    echo $k . " "; // 0 1 2 3 4
    $k++;
  } while ($k < 5);

  // Foreach Loop
  $colors = array("red", "green", "blue");
  foreach ($colors as $color) {
    echo $color . " "; // red green blue
  }
  ?>

PHP Functions:

  • PHP functions allow for reusable and modular code
  • Functions can accept parameters and return values
  • Syntax for defining a function:
  function function_name (parameter1, parameter2, ...) {
    code to be executed;
  }
  • Example of defining and using functions:
  <?php
  // Defining a function
  function greet($name) {
    return "Hello, " . $name . "!";
  }

  // Using a function
  $message = greet("John");
  echo $message; // Hello, John!

  // Function with default parameter
  function greetWithTime($name, $time = "morning") {
    return "Good " . $time . ", " . $name . "!";
  }

  // Using function with default parameter
  $message = greetWithTime("Jane");
  echo $message; // Good morning, Jane!
  ?>

PHP Arrays:

  • PHP arrays are used to store collections of data
  • Arrays can be indexed, associative, or multi-dimensional
  • Syntax for defining arrays:
  // Indexed Array
  $cars = array("Toyota", "Honda", "Nissan");

  // Associative Array
  $age = array("John" => 25, "Jane" => 30, "Jim" => 35);

  // Multi-dimensional Array
  $student = array(
    array("John", 25, "Male"),
    array("Jane", 30, "Female"),
    array("Jim", 35, "Male")
  );
  • Example of using arrays:
  <?php
  // Indexed Array
  $cars = array("Toyota", "Honda", "Nissan");
  echo $cars[0]; // Toyota

  // Associative Array
  $age = array("John" => 25, "Jane" => 30, "Jim" => 35);
  echo $age['John']; // 25

  // Multi-dimensional Array
  $student = array(
    array("John", 25, "Male"),
    array("Jane", 30, "Female"),
    array("Jim", 35, "Male")
  );
  echo $student[1][0]; // Jane
  ?>

Advance Java MCQ Questions and Answers

PHP Strings and Regular Expressions:

  • PHP strings are sequences of characters used to store and manipulate text data
  • PHP regular expressions are patterns used to match, search, and manipulate strings
  • String functions in PHP:
    • strlen() – get string length
    • strpos() – find position of first occurrence of a string
    • str_replace() – replace all occurrences of the search string with replacement string
    • substr() – extract part of a string
  • Syntax for defining regular expressions:
    • preg_match() – performs a regular expression match
    • preg_match_all() – performs a global regular expression match
    • preg_replace() – performs a search and replace using regular expressions
  • Example of using strings and regular expressions:
  <?php
  // String Functions
  $string = "Hello World";
  echo strlen($string); // 11
  echo strpos($string, "World"); // 6
  echo str_replace("World", "PHP", $string); // Hello PHP

  // Regular Expressions
  $email = "user@example.com";
  $pattern = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,5}$/";
  if (preg_match($pattern, $email)) {
    echo "valid email";
  } else {
    echo "invalid email";
  }
  ?>

PHP File Handling:

  • PHP file handling is used to read, write, and manipulate files on the server
  • File functions in PHP:
    • fopen() – opens a file or URL
    • fread() – reads a file
    • fwrite() – writes to a file
    • fclose() – closes a file
    • file_get_contents() – reads entire file into a string
    • file_put_contents() – writes data to a file
  • Example of using file functions:
  <?php
  // Writing to a File
  $file = "test.txt";
  $handle = fopen($file, "w");
  $text = "Hello PHP";
  fwrite($handle, $text);
  fclose($handle);

  // Reading from a File
  $file = "test.txt";
  $handle = fopen($file, "r");
  $text = fread($handle, filesize($file));
  echo $text;
  fclose($handle);

  // Reading and Writing using file_get_contents and file_put_contents
  $file = "test.txt";
  $text = "Hello PHP";
  file_put_contents($file, $text);
  $text = file_get_contents($file);
  echo $text;
  ?>

PHP Cookies and Sessions:

  • PHP cookies are used to store data on the client side and persist across multiple requests
  • PHP sessions are used to store data on the server side and persist across multiple requests
  • Cookie functions in PHP:
    • setcookie() – sets a cookie
    • $_COOKIE – an array of all sent cookies
  • Session functions in PHP:
    • session_start() – starts a session
    • $_SESSION – an array of all session variables
    • session_destroy() – destroys all session data
  • Example of using cookies and sessions:
  <?php
  // Cookies
  setcookie("username", "John Doe", time() + (86400 * 30), "/");
  if (isset($_COOKIE["username"])) {
    echo "Welcome " . $_COOKIE["username"];
  }

  // Sessions
  session_start();
  $_SESSION["username"] = "John Doe";
  echo "Welcome " . $_SESSION["username"];
  session_destroy();
  ?>

PHP MySQL Database Connections:

  • PHP can be used to connect and interact with a MySQL database
  • PHP MySQL functions:
    • mysqli_connect() – connects to a MySQL database
    • mysqli_query() – executes a query on a MySQL database
    • mysqli_fetch_assoc() – fetches a result row as an associative array
    • mysqli_close() – closes a MySQL connection
  • Example of connecting to a MySQL database and executing a query:
  <?php
  // Connect to MySQL database
  $servername = "localhost";
  $username = "username";
  $password = "password";
  $dbname = "databasename";
  $conn = mysqli_connect($servername, $username, $password, $dbname);

  // Execute a query
  $sql = "SELECT * FROM users";
  $result = mysqli_query($conn, $sql);

  // Fetch and display result
  while ($row = mysqli_fetch_assoc($result)) {
    echo "id: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
  }

  // Close connection
  mysqli_close($conn);
  ?>

PHP Exception Handling:

  • PHP Exception handling is used to handle errors and exceptions in a program
  • PHP Exception functions:
    • try – a block of code to try and test for exceptions
    • throw – throws an exception
    • catch – catches an exception and handles it
  • Example of PHP Exception handling:
  <?php
  function divide($a, $b) {
    if ($b == 0) {
      throw new Exception("Cannot divide by zero");
    }
    return $a / $b;
  }

  try {
    echo divide(10, 2) . "<br>";
    echo divide(10, 0) . "<br>";
  } catch (Exception $e) {
    echo "Error: " . $e->getMessage();
  }
  ?>

PHP OOP Concepts:

  • PHP Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects”
  • Key concepts in PHP OOP:
    • Class – blueprint for creating objects
    • Object – instance of a class
    • Property – variables inside a class
    • Method – functions inside a class
    • Inheritance – allows one class to inherit properties and methods from another class
    • Polymorphism – allows objects to take on different forms
  • Example of PHP OOP class and object creation:
  <?php
  class User {
    public $name;
    public $age;

    public function __construct($name, $age) {
      $this->name = $name;
      $this->age = $age;
    }

    public function displayName() {
      return "Name: " . $this->name;
    }

    public function displayAge() {
      return "Age: " . $this->age;
    }
  }

  $user1 = new User("John", 25);
  echo $user1->displayName() . "<br>";
  echo $user1->displayAge() . "<br>";
  ?>

PHP Built-in Functions:

PHP has a large number of built-in functions for various tasks such as:

  • String manipulation (strlen, strpos, strtolower)
  • Array manipulation (array_keys, array_values, array_push)
  • Date/Time (date, time, mktime)
  • Mathematics (max, min, abs)