ClickCease

PHP Programming

1. Basic Syntax


<?php
// Single-line comment
# Another single-line comment
/*
Multi-line comment
*/

2. Variables


$variable_name = "value";  // String
$number = 123;             // Integer
$float = 12.34;            // Float
$array = array(1, 2, 3);   // Array

3. Data Types

  • String
  • Integer
  • Float
  • Boolean
  • Array
  • Object
  • NULL

4. Operators

  • Arithmetic: +, -, *, /, %
  • Assignment: =, +=, -=, *=, /=
  • Comparison: ==, ===, !=, !==, <, >, <=, >=
  • Logical: &&, ||, !

5. Control Structures

If Statement:


if ($condition) {
    // code to execute
} elseif ($another_condition) {
    // code to execute
} else {
    // code to execute
}
Switch Statement:

switch ($variable) {
    case 'value1':
        // code
        break;
    case 'value2':
        // code
        break;
    default:
        // code
}
Loops:

// For loop
for ($i = 0; $i < 10; $i++) {
    // code
}
// While loop
while ($condition) {
    // code
}
// Foreach loop (for arrays)
foreach ($array as $value) {
    // code
}

6. Functions


function functionName($parameter) {
    // code
    return $value;
}

7. Superglobals

  • $_GET – Used to collect data sent in the URL.
  • $_POST – Used to collect data sent in an HTTP POST request.
  • $_SESSION – Used to store session variables.
  • $_COOKIE – Used to retrieve cookies.
  • $_FILES – Used to handle file uploads.

8. String Functions


strlen($string);      // Length of a string
strpos($string, $needle);  // Find position of first occurrence
str_replace($search, $replace, $subject); // Replace all occurrences

9. Array Functions


array_push($array, $value);   // Add element to the end
array_pop($array);            // Remove last element
count($array);                // Count elements in an array
sort($array);                 // Sort an array

10. File Handling


$file = fopen("file.txt", "r"); // Open file
$content = fread($file, filesize("file.txt")); // Read file
fclose($file); // Close file
file_get_contents("file.txt"); // Read file as a string
file_put_contents("file.txt", $data); // Write data to a file

11. Error Handling


try {
    // code that may throw an exception
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "n";
}

12. Database Connection (PDO)


try {
    $pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // Execute queries...
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

13. Best Practices

  • Always validate user input.
  • Use prepared statements to prevent SQL injection.
  • Keep code organized with proper indentation and comments.
  • Use version control (like Git) for your code.

Download Elysium Spark Note

Facebook
X
LinkedIn
Pinterest
WhatsApp