UNIT III (Strings and Arrays)
UNIT III (Strings and Arrays)
Arrays)
Prepared By: Ukesh Bhattarai
String
<?php
$first = "Hello";
$second = "World";
echo $first . " " . $second;
?>
3. Common String Functions
PHP provides many functions for string manipulation:
Case-Sensitivity in Constants
By default, constants are case-sensitive in PHP.
<?php
define("LANGUAGE", "PHP");
echo LANGUAGE; // Works
echo language; // Error (Undefined constant)
?>
Printing Strings
PHP provides multiple ways to print strings, including echo, print, and
printf. Each has its own use case.
Using echo (Most Common)
echo is the fastest and most commonly used method to display output.
These encoding and escaping techniques help in security, safe storage, and
proper rendering of data in PHP applications.
Comparing Strings in PHP
Comparing strings is useful for checking equality, sorting, and authentication
purposes.
Using Comparison Operators (==, ===, !=, !==)
== checks if two strings have the same value (ignores type).
=== checks both value and data type (strict comparison).
!= or !== checks if two strings are different.
<?php
$str1 = "Hello";
$str2 = "hello";
if ($str1 == $str2) {
echo "Strings are equal!";
} else {
echo "Strings are not equal!";
}
// Output: Strings are not equal! (Case-sensitive)
?>
Using strcasecmp() (Case-Insensitive Comparison)
Returns 0 if both strings are equal (ignores case).
Returns a positive number if the first string is greater.
Returns a negative number if the second string is greater.
<?php
echo strcasecmp("Hello", "hello"); // Output: 0 (Equal, case ignored)
?>
<?php
echo str_starts_with("Hello PHP!", "Hello"); // Output: 1 (true)
echo str_ends_with("Hello PHP!", "PHP!"); // Output: 1 (true)
?>
Comparing Strings helps in equality checks and sorting.
Manipulating Strings allows modifications like changing case, trimming spaces,
and replacing words.
Searching Strings helps find specific words, positions, and patterns.
Array
An array in PHP is a data structure that stores multiple values in a single variable.
It allows you to group related items together and access them using keys or
indices.
Why Use Arrays?
Store multiple values in a single variable
Efficiently manage large datasets
Perform operations like sorting, filtering, and searching
Output:
Name: Alice, Age: 25, Job: Engineer
Extracting Key-Value Pairs from an Associative Array (extract())
The extract() function creates variables from array keys.
$user = ["name" => "Bob", "email" => "[email protected]", "age" => 30];
extract($user);
Output:
print_r($person);
Output:
Array ( [name] => Alice [age] => 25 [city] => New York )
Converting an Associative Array to Variables
Using extract()
The extract() function converts an associative array into separate variables,
where keys become variable names.
$person = ["name" => "Bob", "email" => "[email protected]", "age" => 30];
extract($person);
echo "Name: $name, Email: $email, Age: $age";
Output:
Name: Bob, Email: [email protected], Age: 30