Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

PHP Basic Syntax and Control Structures

Tech Apr 20 11

Variables

Variables in PHP start with a $ symbol followed by the variable name. Variable names must begin with a letter or underscore, and can only contain letters, digits, and underscores (A-z, 0-9, _). They are case-sensitive ($y and $Y are different variables). The var_dump() function outputs the type and value of a variable, commonly used for debugging.

Example:

$mumu = 1111;
$didi = 2222;
$didi =& $mumu; // Reference assignment
$mumu = 8888;
echo $didi; // Output: 8888

This behavior mimics shared data — when $didi references $mumu, changing $mumu also affects $didi.

Variable Assignment Types:

  • Direct Copy: $new_name = $name;
  • Reference Assignment: $new_name2 = &$name; — changes to one affect the other.
  • Variable Variables: Using $$$name to dynamically access variables based on string values.

Constants

Constants are defined using define() and cannot be changed after definition. They do not use $ and are typically written in uppercase for clarity.

define('NAME', '赵六');
echo NAME; // Output: 赵六

Use defined("NAME") to check if a constant exists.


Data Types

PHP supports three main categories:

  1. Scalar Types:

    • int: integers (e.g., 100)
    • float: floating-point numbers (e.g., 100.24)
    • string: text (e.g., "Hello")
    • bool: boolean (true/false)
  2. Compound Types:

    • array: ordered collections (e.g., [1, 2, 3])
    • object: instances of classes (e.g., new People())
  3. Special Types:

    • null: represents no value
    • resource: handles external resources (e.g., file pointers)

Example:

$arr = [1, 3, 4];
var_dump($arr);

class People {
    public $name = "123";
}
$peo = new People();
var_dump($peo);

Type Conversion and Operators

Implicit Type Casting

PHP automatically converts types during operations:

$num = 100;
$float_val = 20.01;
var_dump($num + $float_val); // float(120.01)

// String to int: stops at first non-digit
$str = "100.01aaaa";
var_dump($str + 10); // int(110)

Explicit Type Casting

Use functions like intval(), floatval(), and boolval():

$str = "101abc";
var_dump(intval($str));     // int(101)
var_dump(floatval($str));   // float(101)
var_dump(boolval($str));    // bool(true) (non-empty string)

Type Checking Functions

var_dump(is_bool(true));      // true
var_dump(is_string("abc"));  // true
var_dump(is_array([1]));      // true

Operators

  • Arithmetic: +, -, *, /, %, ++, --
  • String Concatenation: ., e.g., $name . "" . $age
  • Assignment: +=, -=, *=, /=, %=
  • Comparison: ==, ===, !=, !==, <, >, <=, >=
  • Logical: and, or, !
  • Ternary: condition ? true_value : false_value

Example:

echo 100 > 50 ? "yes" : "no"; // Output: yes

Control Flow

Sequential Execution

echo "1";
echo "2";
echo "3";

Conditional Branching

if (1 < 2) {
    echo "Expression is true";
} else {
    echo "False";
}

$age = 17;
if ($age >= 18) {
    echo "You can play freely";
} else {
    echo "Underage – limit gameplay to 2 hours";
}

Multi-way Branching

$age = 35;
if ($age < 18) {
    echo "Underage";
} elseif ($age <= 30) {
    echo "Play freely";
} elseif ($age <= 50) {
    echo "Consider spending money";
} else {
    echo "Senior, take care of your health";
}

Loops

  • For Loop:
for ($i = 0; $i < 10; $i++) {
    echo $i . "<br>";
}
  • While Loop:
$num = 1;
while ($num <= 10) {
    $num++;
    if ($num == 5) continue; // Skip iteration
    echo $num;
}
  • Do-While Loop:
$num = 1;
do {
    echo "Loop body";
    echo $num;
} while ($num > 10); // Executes at least once
  • Foreach Loop (for arrays):
$arr = ['a', 'b', 'c'];
foreach ($arr as $key => $value) {
    echo "Key: $key, Value: $value<br>";
}

Functions

Functions are reusable blocks of code.

Function Definition

function greet($name) {
    echo "Hello, $name!<br>";
}

// Call function
greet("Alice"); // Output: Hello, Alice!

Parameters and Return Values

  • Parameters: Passed by value (copy), unless referenced with &
  • Return Values: Use return to send back results
function add($a, $b) {
    return $a + $b;
}
$result = add(5, 3);
var_dump($result); // int(8)

Default Parameters

function greet($name, $greeting = "Hi") {
    echo "$greeting, $name!<br>";
}
greet("Bob");        // Hi, Bob!
greet("Charlie", "Hey"); // Hey, Charlie!

Scope and Global Variables

  • Local Variables: Defined inside a function
  • Global Variables: Accessible via global keyword
$name = "Tom";
function showName() {
    global $name;
    echo $name;
}
showName(); // Output: Tom

Static Variables

Persist between function calls:

function counter() {
    static $count = 0;
    $count++;
    echo $count . "<br>";
}

counter(); // 1
counter(); // 2

Variable Functions

Functions can be called dynamically using variable names:

$func_name = "counter";
$func_name(); // Calls counter()

Arrays

Arrays store multiple values under a single variable.

Indexed Array

$arr = array('dong', '18', '网络安全专家');
echo $arr[2]; // Output: 网络安全专家

Associative Array

$arr = array(
    'name' => 'dong',
    'age' => '18',
    'profession' => '网络安全专家'
);

foreach ($arr as $key => $value) {
    echo "Key: $key, Value: $value<br>";
}

Multidimensional Array

$arr = array(
    'name' => 'dong',
    'age' => '18',
    'skills' => array('网络安全', '网络工程')
);

foreach ($arr as $key => $value) {
    if (is_array($value)) {
        foreach ($value as $sub_key => $sub_value) {
            echo "Sub-array: $sub_value<br>";
        }
    } else {
        echo "Key: $key, Value: $value<br>";
    }
}

Timestamps

Convert time to Unix timestamp and back:

$timestamp = time();
echo $timestamp . "<hr>";
echo date('Y-m-d H:i:s', $timestamp); // Output: 2020-06-10 08:33:21

GET and POST Requests

  • GET: Used for retrieving data (e.g., http://example.com/page.php?name=dong)
  • POST: Used for sending data (e.g., form submissions)

Access data via superglobals:

var_dump($_GET); // Get query parameters
$l = $_GET['mumu'];
file_put_contents("./22.txt", $l); // Save to file

Ternary Operator

Short-hand conditional expression:

$a = 1 ? "2343" : "300"; // Result: "2343"

// Safe default handling
$b = isset($_GET['name']) ? $_GET['name'] : "default";

Use empty() to check for empty values, isset() to check existance.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.