Module 2: PHP String Operators
Learning Objectives
- Master PHP operators
- Understand operator precedence
- Apply operators in practical scenarios
- Write efficient expressions
Introduction to PHP String Operators
Welcome to our session on PHP String Operators! Strings are one of the most common data types in web development, used for everything from displaying text to users to storing and manipulating data. PHP provides specialized operators designed to work with strings, making text manipulation efficient and intuitive.
Think of string operators as the tools that help you weave words and text together in your applications. Just as a storyteller combines words to create narratives, PHP string operators allow you to combine, modify, and work with text in powerful ways. Today, we'll explore these operators, understand how they work, and see them in action through practical examples relevant to web development.
String Operators Overview
PHP provides two primary string operators that enable you to work with text:
| Operator | Name | Example | Result |
|---|---|---|---|
| . | Concatenation | $a . $b | Concatenation of $a and $b |
| .= | Concatenation assignment | $a .= $b | Appends $b to $a |
While these might seem like just two simple operators, they form the foundation of text manipulation in PHP and can be combined with other PHP features to create powerful string handling capabilities.
Concatenation Operator (.)
The concatenation operator (.) combines two strings into one. It's represented by a period/dot and acts as a "glue" to join strings together.
Basic Concatenation Examples
<?php
// Basic concatenation examples
$firstName = "John";
$lastName = "Doe";
// Using the concatenation operator (.)
$fullName = $firstName . " " . $lastName;
echo $fullName; // Output: John Doe
// Concatenating multiple strings
$greeting = "Hello, " . $firstName . " " . $lastName . "!";
echo $greeting; // Output: Hello, John Doe!
// Building a sentence
$age = 25;
$city = "New York";
$sentence = "My name is " . $fullName . ", I am " . $age . " years old and live in " . $city . ".";
echo $sentence;
// Output: My name is John Doe, I am 25 years old and live in New York.
?>
Concatenation vs. Addition
It's important to understand the difference between concatenation (.) and addition (+) in PHP:
<?php
// Understanding the difference between concatenation and addition
$num1 = "5";
$num2 = "3";
// String concatenation with the dot operator
$concatenated = $num1 . $num2;
echo "Concatenation: " . $concatenated; // Output: Concatenation: 53
// Mathematical addition with the plus operator
$added = $num1 + $num2;
echo "Addition: " . $added; // Output: Addition: 8
// Be careful with types!
$a = "10";
$b = "20";
echo $a . $b; // Output: 1020 (string concatenation)
echo $a + $b; // Output: 30 (mathematical addition)
// Mixing operators requires parentheses for clarity
$price = 10;
$quantity = 3;
echo "Total: $" . ($price * $quantity); // Output: Total: $30
?>
Type Conversion in Concatenation
PHP automatically converts non-string values to strings when concatenating:
<?php
// Type conversion in concatenation
$integer = 42;
$float = 3.14159;
$boolean = true;
$null = null;
// PHP automatically converts types to strings
echo "Integer: " . $integer; // Output: Integer: 42
echo "Float: " . $float; // Output: Float: 3.14159
echo "Boolean: " . $boolean; // Output: Boolean: 1 (true becomes 1)
echo "Boolean: " . false; // Output: Boolean: (false becomes empty string)
echo "Null: " . $null; // Output: Null: (null becomes empty string)
// Objects need __toString() method
class User {
public $name = "Alice";
public function __toString() {
return $this->name;
}
}
$user = new User();
echo "User: " . $user; // Output: User: Alice
// Arrays cannot be concatenated directly
$array = [1, 2, 3];
// echo "Array: " . $array; // Warning: Array to string conversion
echo "Array: " . implode(", ", $array); // Output: Array: 1, 2, 3
?>
Real-World Application: Dynamic HTML Generation
String concatenation is extremely useful for building HTML dynamically:
<?php
// Building HTML dynamically with concatenation
$products = [
['id' => 1, 'name' => 'Laptop', 'price' => 999.99, 'stock' => 5],
['id' => 2, 'name' => 'Mouse', 'price' => 29.99, 'stock' => 15],
['id' => 3, 'name' => 'Keyboard', 'price' => 79.99, 'stock' => 8]
];
// Build HTML table
$html = '<table class="products-table">' . "\n";
$html .= ' <thead>' . "\n";
$html .= ' <tr>' . "\n";
$html .= ' <th>Product</th>' . "\n";
$html .= ' <th>Price</th>' . "\n";
$html .= ' <th>Stock</th>' . "\n";
$html .= ' <th>Action</th>' . "\n";
$html .= ' </tr>' . "\n";
$html .= ' </thead>' . "\n";
$html .= ' <tbody>' . "\n";
foreach ($products as $product) {
$html .= ' <tr>' . "\n";
$html .= ' <td>' . htmlspecialchars($product['name']) . '</td>' . "
";
$html .= ' <td>$' . number_format($product['price'], 2) . '</td>' . "
";
$html .= ' <td>' . $product['stock'] . ' units</td>' . "
";
$html .= ' <td><button onclick="addToCart(' . $product['id'] . ')">Add to Cart</button></td>' . "
";
$html .= ' </tr>' . "
";
}
$html .= ' </tbody>' . "
";
$html .= '</table>';
echo $html;
?>
Real-World Application: Building an Email Template
The concatenation assignment operator is perfect for building longer texts like email templates:
<?php
// Building an email template with concatenation assignment
$customerName = "Sarah Johnson";
$orderNumber = "ORD-2024-1234";
$orderDate = date('F j, Y');
$products = [
['name' => 'PHP Book', 'quantity' => 1, 'price' => 39.99],
['name' => 'WordPress Guide', 'quantity' => 2, 'price' => 29.99]
];
// Start building the email
$email = "Dear " . $customerName . ",\n\n";
$email .= "Thank you for your order!\n\n";
$email .= "Order Details:\n";
$email .= "================================\n";
$email .= "Order Number: " . $orderNumber . "\n";
$email .= "Order Date: " . $orderDate . "\n\n";
$email .= "Items Ordered:\n";
$email .= "--------------------------------\n";
$total = 0;
foreach ($products as $product) {
$lineTotal = $product['quantity'] * $product['price'];
$email .= $product['name'] . " (x" . $product['quantity'] . ") - $" . number_format($lineTotal, 2) . "\n";
$total += $lineTotal;
}
$email .= "--------------------------------\n";
$email .= "Total: $" . number_format($total, 2) . "\n\n";
$email .= "Your order will be shipped within 2-3 business days.\n\n";
$email .= "Best regards,\n";
$email .= "The Store Team";
echo nl2br($email); // Convert newlines to HTML breaks for display
?>
Performance Considerations
When building large strings in PHP, there are performance implications to consider:
<?php
// Performance comparison: concatenation methods
// Method 1: Using concatenation operator
$start = microtime(true);
$result1 = '';
for ($i = 0; $i < 10000; $i++) {
$result1 = $result1 . 'a';
}
$time1 = microtime(true) - $start;
echo "Method 1 (. operator): " . number_format($time1, 6) . " seconds\n";
// Method 2: Using concatenation assignment
$start = microtime(true);
$result2 = '';
for ($i = 0; $i < 10000; $i++) {
$result2 .= 'a';
}
$time2 = microtime(true) - $start;
echo "Method 2 (.= operator): " . number_format($time2, 6) . " seconds\n";
// Method 3: Using array and implode (often fastest for large strings)
$start = microtime(true);
$parts = [];
for ($i = 0; $i < 10000; $i++) {
$parts[] = 'a';
}
$result3 = implode('', $parts);
$time3 = microtime(true) - $start;
echo "Method 3 (array + implode): " . number_format($time3, 6) . " seconds\n";
// Show which method was fastest
$times = ['Method 1' => $time1, 'Method 2' => $time2, 'Method 3' => $time3];
asort($times);
$fastest = array_key_first($times);
echo "\nFastest method: " . $fastest;
?>
Performance Tips:
- Using
.=is generally more efficient than using$a = $a . $b - For building very large strings, using an array and
implode()often provides better performance - Modern PHP versions have significantly improved string concatenation performance
Analogy: The concatenation assignment operator is like a sticky note pad where you keep adding more notes to the bottom. Each time you use .=, you're sticking another note to your growing collection, building it up piece by piece.
String Interpolation (An Alternative to Concatenation)
While not technically an operator, string interpolation offers an alternative to concatenation for combining strings and variables. In PHP, variables within double-quoted strings are automatically replaced with their values.
Basic String Interpolation Examples
<?php
// String interpolation with double quotes
$name = "Alice";
$age = 28;
$city = "San Francisco";
// Variables are automatically replaced in double quotes
echo "Hello, my name is $name"; // Output: Hello, my name is Alice
echo "I am $age years old"; // Output: I am 28 years old
echo "I live in $city"; // Output: I live in San Francisco
// Complex expressions need curly braces
$price = 100;
$quantity = 3;
echo "Total cost: \${$price * $quantity}"; // Output: Total cost: $300
// Array elements and object properties
$user = ['name' => 'Bob', 'email' => 'bob@example.com'];
echo "User: {$user['name']}, Email: {$user['email']}";
// Output: User: Bob, Email: bob@example.com
// Single quotes don't interpolate
echo 'Hello, $name'; // Output: Hello, $name (literal)
// Escape sequences in double quotes
echo "Line 1\nLine 2\tTabbed"; // Newline and tab work
echo 'Line 1\nLine 2\tTabbed'; // Treated as literal text
?>
Concatenation vs. Interpolation: When to Use Each
| Aspect | Concatenation (.) | Interpolation (Double Quotes) |
|---|---|---|
| Readability | Can be harder to read with complex strings | Often more readable for simple variable inclusions |
| Complexity | Better for complex expressions | Requires curly braces for complex expressions |
| Performance | Generally similar for modern PHP | Slightly slower due to parsing, but negligible in most cases |
| Special Characters | No need to escape quotes or variables | Must escape double quotes (\") and dollar signs (\$) |
| Recommended For | Building HTML, complex string operations | Simple messages, readable text with few variables |
Examples Comparing Both Approaches
<?php
// Comparing concatenation vs interpolation
$firstName = "John";
$lastName = "Smith";
$age = 30;
$occupation = "Developer";
// Using concatenation
$intro1 = "My name is " . $firstName . " " . $lastName . ". I am " . $age . " years old and work as a " . $occupation . ".";
// Using interpolation
$intro2 = "My name is $firstName $lastName. I am $age years old and work as a $occupation.";
// Both produce the same output
echo $intro1 . "\n";
echo $intro2 . "\n";
// For HTML generation
// Concatenation approach (clearer for complex HTML)
$html1 = '<div class="user">' .
'<h2>' . htmlspecialchars($firstName . ' ' . $lastName) . '</h2>' .
'<p>Age: ' . $age . '</p>' .
'<p>Job: ' . htmlspecialchars($occupation) . '</p>' .
'</div>';
// Interpolation approach (can get messy with quotes)
$html2 = "<div class=\"user\">
<h2>{$firstName} {$lastName}</h2>
<p>Age: {$age}</p>
<p>Job: {$occupation}</p>
</div>";
?>
Real-World Application: Template System
String interpolation and concatenation can be combined to create a simple template system:
<?php
// Simple template system using string interpolation and concatenation
class Template {
private $vars = [];
public function assign($key, $value) {
$this->vars[$key] = $value;
}
public function render($template) {
// Extract variables for interpolation
extract($this->vars);
// Use output buffering to capture the template
ob_start();
eval('?>' . $template);
return ob_get_clean();
}
}
// Usage example
$tpl = new Template();
$tpl->assign('title', 'Welcome Page');
$tpl->assign('username', 'John Doe');
$tpl->assign('messages', 5);
$template = '<!DOCTYPE html>
<html>
<head>
<title><?= $title ?></title>
</head>
<body>
<h1>Welcome, <?= $username ?>!</h1>
<p>You have <?= $messages ?> new messages.</p>
</body>
</html>';
echo $tpl->render($template);
?>
Analogy: String interpolation is like a form letter where you've left blanks to be filled in with specific information. Instead of cutting and pasting different pieces together (concatenation), you have a complete template where variables are automatically replaced with their values.
Heredoc and Nowdoc Syntax
For handling multi-line strings, PHP provides Heredoc and Nowdoc syntax, which offer alternatives to concatenation for creating complex strings.
Heredoc Syntax
Heredoc syntax works like double-quoted strings and allows variable interpolation:
<?php
// Heredoc syntax - works like double quotes
$name = "Alice";
$product = "PHP Course";
$price = 49.99;
$emailContent = <<<EOT
Dear $name,
Thank you for your interest in our $product!
Special offer just for you:
- Product: $product
- Regular Price: \$price
- Your Discount: 20%
- Final Price: \${$price * 0.8}
This offer expires soon, so don't miss out!
Best regards,
The Sales Team
EOT;
echo $emailContent;
// Heredoc for HTML
$html = <<<HTML
<div class="product-card">
<h2>$product</h2>
<p class="price">\$price</p>
<button>Buy Now</button>
</div>
HTML;
echo $html;
?>
Nowdoc Syntax
Nowdoc syntax (with single quotes) works like single-quoted strings and does not process variables:
<?php
// Nowdoc syntax - works like single quotes (no variable interpolation)
$name = "Bob";
$variable = "test";
// Note the single quotes around the identifier
$codeExample = <<<'CODE'
This is a PHP code example:
<?php
$name = "John";
$age = 30;
echo "My name is $name and I am $age years old.";
?>
Notice that $name and $variable are NOT replaced.
This is perfect for code examples and documentation.
CODE;
echo $codeExample;
// Nowdoc for SQL queries
$sql = <<<'SQL'
SELECT users.name, orders.total
FROM users
INNER JOIN orders ON users.id = orders.user_id
WHERE orders.total > 100
AND users.status = 'active'
ORDER BY orders.created_at DESC;
SQL;
echo "Query to execute:\n" . $sql;
?>
Real-World Application: Email Template with Heredoc
Heredoc is ideal for creating email templates or other multi-line text:
<?php
// Email template using Heredoc
function sendWelcomeEmail($user) {
$name = $user['name'];
$email = $user['email'];
$username = $user['username'];
$activationLink = "https://example.com/activate?token=" . $user['token'];
$currentYear = date('Y');
$emailBody = <<<EMAIL
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial, sans-serif; line-height: 1.6; }
.container { max-width: 600px; margin: 0 auto; padding: 20px; }
.header { background: #007bff; color: white; padding: 20px; text-align: center; }
.content { padding: 20px; background: #f4f4f4; }
.button { display: inline-block; padding: 10px 20px; background: #28a745; color: white; text-decoration: none; border-radius: 5px; }
.footer { text-align: center; padding: 20px; color: #666; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Welcome to Our Platform!</h1>
</div>
<div class="content">
<h2>Hello, $name!</h2>
<p>Thank you for registering with us. Your account has been created successfully.</p>
<p><strong>Your Details:</strong></p>
<ul>
<li>Name: $name</li>
<li>Email: $email</li>
<li>Username: $username</li>
</ul>
<p>To activate your account, please click the button below:</p>
<p style="text-align: center;">
<a href="$activationLink" class="button">Activate Account</a>
</p>
<p><small>Or copy this link: $activationLink</small></p>
</div>
<div class="footer">
<p>© $currentYear Your Company. All rights reserved.</p>
</div>
</div>
</body>
</html>
EMAIL;
return $emailBody;
}
// Usage
$newUser = [
'name' => 'Jane Smith',
'email' => 'jane@example.com',
'username' => 'janesmith',
'token' => 'abc123xyz789'
];
echo sendWelcomeEmail($newUser);
?>
When to Use Different String Syntax
| Syntax | Variables? | Best For |
|---|---|---|
| Single Quotes (') | No | Simple strings with no variables |
| Double Quotes (") | Yes | Simple strings with variables |
| Concatenation (.) | - | Building strings dynamically, complex expressions |
Heredoc (<<| Yes |
Multi-line strings with variables (emails, templates) |
|
| Nowdoc (<<<'EOT') | No | Multi-line strings without variable processing (code examples, SQL) |
Beyond Basic String Operators
While concatenation and concatenation assignment are the primary string operators in PHP, the language offers many powerful string functions that complement these operators.
Common String Functions
<?php
// Common string functions that complement string operators
$text = "Hello World";
$email = "john.doe@example.com";
$sentence = " PHP is a great language ";
// String length
echo strlen($text); // Output: 11
// Convert case
echo strtoupper($text); // Output: HELLO WORLD
echo strtolower($text); // Output: hello world
echo ucfirst("hello"); // Output: Hello
echo ucwords("hello world"); // Output: Hello World
// Find and replace
echo str_replace("World", "PHP", $text); // Output: Hello PHP
echo str_ireplace("world", "PHP", $text); // Case-insensitive replace
// Substring operations
echo substr($text, 0, 5); // Output: Hello
echo substr($text, -5); // Output: World
echo substr($text, 6, 3); // Output: Wor
// Find position
echo strpos($text, "World"); // Output: 6
echo strrpos($email, "."); // Output: 19 (last occurrence)
// Trimming
echo trim($sentence); // Remove whitespace from both ends
echo ltrim($sentence); // Remove from left
echo rtrim($sentence); // Remove from right
// Splitting and joining
$parts = explode(" ", $text);
print_r($parts); // Array ( [0] => Hello [1] => World )
$joined = implode("-", $parts);
echo $joined; // Output: Hello-World
// Padding
echo str_pad("5", 3, "0", STR_PAD_LEFT); // Output: 005
echo str_pad("PHP", 10, "*", STR_PAD_BOTH); // Output: ***PHP****
// Repeat
echo str_repeat("=", 20); // Output: ====================
?>
Advanced String Operations
<?php
// Advanced string operations
// sprintf for formatted strings
$name = "John";
$age = 25;
$balance = 1234.567;
$formatted = sprintf("Name: %s, Age: %d, Balance: $%.2f", $name, $age, $balance);
echo $formatted; // Output: Name: John, Age: 25, Balance: $1234.57
// String parsing
$data = "name=John&age=25&city=NewYork";
parse_str($data, $result);
print_r($result);
// Array ( [name] => John [age] => 25 [city] => NewYork )
// Regular expressions
$email = "contact@example.com";
if (preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email)) {
echo "Valid email";
}
// Extract numbers from string
$text = "The price is $45.99 for 3 items";
preg_match_all('/\d+\.?\d*/', $text, $matches);
print_r($matches[0]); // Array ( [0] => 45.99 [1] => 3 )
// Word wrap
$longText = "This is a very long sentence that needs to be wrapped at a specific width for better display.";
echo wordwrap($longText, 30, "\n"); // Wrap at 30 characters
// String comparison
$str1 = "Apple";
$str2 = "apple";
echo strcmp($str1, $str2); // Case-sensitive comparison
echo strcasecmp($str1, $str2); // Case-insensitive comparison
// Levenshtein distance (similarity)
$word1 = "kitten";
$word2 = "sitting";
echo levenshtein($word1, $word2); // Output: 3 (edit distance)
// Sound-based comparison
echo soundex("Smith"); // S530
echo soundex("Smythe"); // S530 (sounds similar)
?>
Real-World Application: URL Builder
Combining string operators with string functions can create powerful tools:
<?php
// URL Builder using string operations
class URLBuilder {
private $scheme = 'https';
private $host = '';
private $path = '/';
private $params = [];
private $fragment = '';
public function setScheme($scheme) {
$this->scheme = $scheme;
return $this;
}
public function setHost($host) {
$this->host = $host;
return $this;
}
public function setPath($path) {
$this->path = '/' . ltrim($path, '/');
return $this;
}
public function addParam($key, $value) {
$this->params[$key] = $value;
return $this;
}
public function setFragment($fragment) {
$this->fragment = $fragment;
return $this;
}
public function build() {
// Start with scheme and host
$url = $this->scheme . '://' . $this->host;
// Add path
$url .= $this->path;
// Add query parameters
if (!empty($this->params)) {
$queryParts = [];
foreach ($this->params as $key => $value) {
$queryParts[] = urlencode($key) . '=' . urlencode($value);
}
$url .= '?' . implode('&', $queryParts);
}
// Add fragment
if ($this->fragment) {
$url .= '#' . $this->fragment;
}
return $url;
}
}
// Usage
$url = new URLBuilder();
$finalUrl = $url->setHost('api.example.com')
->setPath('/users/search')
->addParam('q', 'john doe')
->addParam('limit', 10)
->addParam('sort', 'name')
->setFragment('results')
->build();
echo $finalUrl;
// Output: https://api.example.com/users/search?q=john+doe&limit=10&sort=name#results
?>
Best Practices for String Operations
- Choose the right approach: Use concatenation for building strings dynamically, interpolation for readability with simple variables, and Heredoc/Nowdoc for multi-line content.
- Be mindful of performance: For large strings, consider using arrays with
implode()instead of repeated concatenation. - Escape user input: Always use
htmlspecialchars()when outputting user-provided data in HTML to prevent XSS attacks. - Watch for encoding issues: Be aware of character encoding, especially when working with multi-byte characters. Consider using the
mb_*string functions for proper Unicode handling. - Use built-in functions: PHP has a rich set of string functions - leverage them instead of reinventing the wheel.
- Maintain readability: Break long string operations into smaller chunks and use meaningful variable names for intermediate results.
Best Practices Example
<?php
// Best practices example: Building a secure contact form response
function generateContactFormResponse($formData) {
// Validate and sanitize input
$name = htmlspecialchars(trim($formData['name'] ?? ''), ENT_QUOTES, 'UTF-8');
$email = filter_var($formData['email'] ?? '', FILTER_SANITIZE_EMAIL);
$subject = htmlspecialchars(trim($formData['subject'] ?? ''), ENT_QUOTES, 'UTF-8');
$message = htmlspecialchars(trim($formData['message'] ?? ''), ENT_QUOTES, 'UTF-8');
// Check required fields
$errors = [];
if (empty($name)) {
$errors[] = "Name is required";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Valid email is required";
}
if (empty($message)) {
$errors[] = "Message is required";
}
// If there are errors, return error message
if (!empty($errors)) {
$errorHtml = '<div class="alert alert-danger">';
$errorHtml .= '<h4>Please correct the following errors:</h4>';
$errorHtml .= '<ul>';
foreach ($errors as $error) {
$errorHtml .= '<li>' . $error . '</li>';
}
$errorHtml .= '</ul>';
$errorHtml .= '</div>';
return $errorHtml;
}
// Build success response using clean, readable concatenation
$response = '<div class="alert alert-success">';
$response .= '<h4>Thank you for your message!</h4>';
$response .= '<p>We have received your message and will respond within 24 hours.</p>';
$response .= '</div>';
// Build confirmation details
$response .= '<div class="confirmation-details">';
$response .= '<h5>Message Details:</h5>';
$response .= '<dl class="row">';
// Use array for better organization of repetitive HTML
$details = [
'Name' => $name,
'Email' => $email,
'Subject' => $subject ?: '(No subject)',
'Message' => nl2br($message)
];
foreach ($details as $label => $value) {
$response .= '<dt class="col-sm-3">' . $label . ':</dt>';
$response .= '<dd class="col-sm-9">' . $value . '</dd>';
}
$response .= '</dl>';
$response .= '</div>';
return $response;
}
// Example usage
$formData = [
'name' => 'John Doe',
'email' => 'john@example.com',
'subject' => 'Question about services',
'message' => "Hello,\nI would like to know more about your services.\nThank you!"
];
echo generateContactFormResponse($formData);
?>
Practice Exercises
Test your understanding of PHP string operators with these exercises:
Exercise 1: String Concatenation Challenge
Create a PHP script that builds an HTML table from an array of data using string concatenation.
<?php
// Exercise 1: String Concatenation Challenge
// Build an HTML table from an array of data
$students = [
['id' => 1, 'name' => 'Alice Johnson', 'grade' => 'A', 'score' => 95],
['id' => 2, 'name' => 'Bob Smith', 'grade' => 'B', 'score' => 87],
['id' => 3, 'name' => 'Charlie Brown', 'grade' => 'A', 'score' => 92],
['id' => 4, 'name' => 'Diana Prince', 'grade' => 'C', 'score' => 78],
['id' => 5, 'name' => 'Edward Norton', 'grade' => 'B', 'score' => 85]
];
function buildStudentTable($students) {
// Start building the table
$html = '<table class="table table-striped">' . "\n";
// Add table header
$html .= ' <thead>' . "\n";
$html .= ' <tr>' . "\n";
$html .= ' <th>ID</th>' . "\n";
$html .= ' <th>Name</th>' . "\n";
$html .= ' <th>Grade</th>' . "\n";
$html .= ' <th>Score</th>' . "\n";
$html .= ' <th>Status</th>' . "\n";
$html .= ' </tr>' . "\n";
$html .= ' </thead>' . "\n";
// Add table body
$html .= ' <tbody>' . "\n";
foreach ($students as $student) {
// Determine status based on score
$status = $student['score'] >= 90 ? 'Excellent' :
($student['score'] >= 80 ? 'Good' : 'Needs Improvement');
// Determine row class based on grade
$rowClass = $student['grade'] === 'A' ? 'table-success' :
($student['grade'] === 'B' ? 'table-info' : 'table-warning');
// Build table row
$html .= ' <tr class="' . $rowClass . '">' . "\n";
$html .= ' <td>' . $student['id'] . '</td>' . "\n";
$html .= ' <td>' . htmlspecialchars($student['name']) . '</td>' . "\n";
$html .= ' <td>' . $student['grade'] . '</td>' . "\n";
$html .= ' <td>' . $student['score'] . '%</td>' . "\n";
$html .= ' <td>' . $status . '</td>' . "\n";
$html .= ' </tr>' . "\n";
}
$html .= ' </tbody>' . "\n";
$html .= '</table>';
return $html;
}
// Display the table
echo buildStudentTable($students);
?>
Exercise 2: URL Query Builder
Create a function that builds a URL query string from an array of parameters.
<?php
// Exercise 2: URL Query Builder
// Create a function that builds a URL query string from an array
function buildQueryString($params, $encode = true) {
if (empty($params)) {
return '';
}
$pairs = [];
foreach ($params as $key => $value) {
// Handle arrays (like checkboxes)
if (is_array($value)) {
foreach ($value as $item) {
$k = $encode ? urlencode($key) . '[]' : $key . '[]';
$v = $encode ? urlencode($item) : $item;
$pairs[] = $k . '=' . $v;
}
}
// Handle null values
elseif ($value === null) {
continue; // Skip null values
}
// Handle boolean values
elseif (is_bool($value)) {
$k = $encode ? urlencode($key) : $key;
$v = $value ? '1' : '0';
$pairs[] = $k . '=' . $v;
}
// Handle regular values
else {
$k = $encode ? urlencode($key) : $key;
$v = $encode ? urlencode($value) : $value;
$pairs[] = $k . '=' . $v;
}
}
return implode('&', $pairs);
}
// Test the function
$params = [
'search' => 'php programming',
'category' => 'tutorials',
'tags' => ['beginner', 'strings', 'operators'],
'sort' => 'date',
'order' => 'desc',
'page' => 1,
'featured' => true,
'draft' => false,
'deleted' => null // This will be skipped
];
$queryString = buildQueryString($params);
echo "Query String: " . $queryString . "\n\n";
// Build complete URL
$baseUrl = 'https://example.com/api/search';
$fullUrl = $baseUrl . '?' . $queryString;
echo "Full URL: " . $fullUrl . "\n\n";
// Alternative: Using http_build_query (built-in function)
$phpQueryString = http_build_query($params);
echo "PHP Built-in: " . $phpQueryString;
?>
Exercise 3: Template System
Create a simple template system that replaces placeholders with values.
<?php
// Exercise 3: Template System
// Create a simple template system that replaces placeholders
class SimpleTemplate {
private $template = '';
private $variables = [];
public function __construct($template = '') {
$this->template = $template;
}
public function setTemplate($template) {
$this->template = $template;
return $this;
}
public function assign($key, $value) {
$this->variables[$key] = $value;
return $this;
}
public function assignArray($array) {
$this->variables = array_merge($this->variables, $array);
return $this;
}
public function render() {
$output = $this->template;
// Replace simple variables {{variable}}
foreach ($this->variables as $key => $value) {
if (!is_array($value) && !is_object($value)) {
$placeholder = '{{' . $key . '}}';
$output = str_replace($placeholder, $value, $output);
}
}
// Handle loops {{#each items}} ... {{/each}}
$output = $this->processLoops($output);
// Handle conditionals {{#if condition}} ... {{/if}}
$output = $this->processConditionals($output);
// Clean up any remaining placeholders
$output = preg_replace('/{{.*?}}/', '', $output);
return $output;
}
private function processLoops($template) {
$pattern = '/{{#each\s+(\w+)}}(.*?){{{\/each}}/s';
return preg_replace_callback($pattern, function($matches) {
$arrayName = $matches[1];
$loopTemplate = $matches[2];
$output = '';
if (isset($this->variables[$arrayName]) && is_array($this->variables[$arrayName])) {
foreach ($this->variables[$arrayName] as $item) {
$itemOutput = $loopTemplate;
if (is_array($item)) {
foreach ($item as $key => $value) {
$itemOutput = str_replace('{{' . $key . '}}', $value, $itemOutput);
}
} else {
$itemOutput = str_replace('{{value}}', $item, $itemOutput);
}
$output .= $itemOutput;
}
}
return $output;
}, $template);
}
private function processConditionals($template) {
$pattern = '/{{#if\s+(\w+)}}(.*?){{{\/if}}/s';
return preg_replace_callback($pattern, function($matches) {
$condition = $matches[1];
$content = $matches[2];
if (isset($this->variables[$condition]) && $this->variables[$condition]) {
return $content;
}
return '';
}, $template);
}
}
// Example usage
$template = '
<h1>{{title}}</h1>
<p>Welcome, {{username}}!</p>
{{#if showMessage}}
<div class="alert">{{message}}</div>
{{/if}}
<h2>Your Orders:</h2>
<ul>
{{#each orders}}
<li>Order #{{id}}: {{product}} - ${{price}}</li>
{{/each}}
</ul>
<p>Total Orders: {{orderCount}}</p>
';
$tpl = new SimpleTemplate($template);
$output = $tpl->assign('title', 'My Shop')
->assign('username', 'John Doe')
->assign('showMessage', true)
->assign('message', 'You have new notifications!')
->assign('orders', [
['id' => 101, 'product' => 'PHP Book', 'price' => '29.99'],
['id' => 102, 'product' => 'MySQL Guide', 'price' => '34.99'],
['id' => 103, 'product' => 'WordPress Course', 'price' => '49.99']
])
->assign('orderCount', 3)
->render();
echo $output;
?>
Summary
In this session, we've explored PHP's string operators and related string handling techniques:
- Concatenation Operator (.): Combines two strings into one, essential for building dynamic content
- Concatenation Assignment (.=): Appends a string to an existing variable, useful for incrementally building strings
- String Interpolation: An alternative to concatenation that embeds variables directly within double-quoted strings
- Heredoc and Nowdoc: Syntax for creating multi-line strings with or without variable interpolation
- Advanced String Manipulation: PHP's rich set of string functions that complement the basic operators
String operators are fundamental to PHP programming as they allow you to create dynamic content, build HTML, format messages, and manipulate text data. Mastering these operators and understanding when to use each approach will help you write more efficient, readable, and maintainable code in your PHP applications.