0% found this document useful (0 votes)
29 views46 pages

UNIT III (Strings and Arrays)

This document provides an overview of strings and arrays in PHP, detailing how to declare, manipulate, and compare strings using various built-in functions. It also explains the different types of arrays (indexed, associative, and multidimensional), how to define and access them, and the benefits of using arrays for managing data. Additionally, it covers string cleaning, encoding, escaping, and searching techniques to enhance data integrity and security.

Uploaded by

ukesh bhattarai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views46 pages

UNIT III (Strings and Arrays)

This document provides an overview of strings and arrays in PHP, detailing how to declare, manipulate, and compare strings using various built-in functions. It also explains the different types of arrays (indexed, associative, and multidimensional), how to define and access them, and the benefits of using arrays for managing data. Additionally, it covers string cleaning, encoding, escaping, and searching techniques to enhance data integrity and security.

Uploaded by

ukesh bhattarai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

UNIT III (Strings and

Arrays)
Prepared By: Ukesh Bhattarai
String

 In PHP, a string is a sequence of characters.


 Strings can be used to store and manipulate text, and PHP provides
several built-in functions to handle string operations.
 1. Declaring Strings in PHP
PHP allows strings to be defined in multiple ways:
Single quotes ('): Interprets the content literally.
Double quotes ("): Allows variable interpolation and escape sequences.
2. String Concatenation (.)
The dot (.) operator is used to concatenate (combine) strings.

<?php
$first = "Hello";
$second = "World";
echo $first . " " . $second;
?>
3. Common String Functions
 PHP provides many functions for string manipulation:

a. strlen() - String Length


Returns the length (number of characters) in a string.
<?php
$str = "Hello, PHP!";
echo strlen($str);
?>
str_word_count() - Word Count
 Counts the number of words in a string.
<?php
$str = "PHP is awesome!";
echo str_word_count($str);
?>

strrev() - Reverse a String


Reverses the given string.
<?php
echo strrev("Hello");
?>
strpos() - Find Position of a Substring
Finds the position of the first occurrence of a substring in a string.
<?php
echo strpos("Hello world", "world");
?>

str_replace() - Replace Text


Replaces all occurrences of a string with another string.
<?php
echo str_replace("world", "PHP", "Hello world!");
?>
strtoupper() and strtolower() - Change Case
Converts a string to uppercase or lowercase.
<?php
echo strtoupper("hello world"); // HELLO WORLD
echo strtolower("HELLO WORLD"); // hello world
?>

substr() - Extract a Substring


Extracts a portion of a string.
<?php
echo substr("Hello World", 6, 5);
?>
trim() - Remove Extra Spaces
Removes whitespace from the beginning and end of a string.
<?php
$str = " Hello PHP ";
echo trim($str);
?>
String Constants
 In PHP, string constants are fixed values that do not change during the
execution of a script.
 PHP allows developers to define their own string constants using the
define() function.
 Syntax:
define("CONSTANT_NAME", "value");
<?php
define("SITE_NAME", "My Awesome Website");
echo "Welcome to " . SITE_NAME;
?>
Constants are global and can be accessed from anywhere in the script.
They cannot be changed or undefined after declaration.
 Using const to Define Constants
Another way to define constants is by using the const keyword.
<?php
const GREETING = "Hello, PHP!";
echo GREETING;
?>

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.

Multiple Arguments in echo


echo can take multiple arguments, separated by commas.
<?php
echo "Hello", " ", "PHP!";
?>
Using printf() (Formatted Output)
printf() allows formatted output, similar to C.
<?php
$name = "John";
$age = 25;
printf("My name is %s and I am %d years old.", $name, $age);
?>
 Using sprintf() (Store Formatted String)
 sprintf() works like printf(), but instead of printing, it returns the formatted
string.
<?php
$name = "Alice";
$formatted = sprintf("Welcome, %s!", $name);
echo $formatted;
?>
 Using var_dump() for Debugging
 var_dump() displays detailed information about a variable.
<?php
$str = "Hello, PHP!";
var_dump($str);
?>

Use echo for general printing.


Use printf() when formatting is needed.
Use var_dump() for debugging.
Accessing Characters in String

 In PHP, strings are treated as arrays of characters, meaning you can


access individual characters using zero-based indexing (like arrays).
1. Using Square Brackets [] or Curly Braces {}
PHP allows accessing string characters using both square brackets ([]) and
curly braces ({}).
<?php
$str = "Hello";
echo $str[0]; // Outputs: H
echo $str[1]; // Outputs: e
?>
2. Accessing the Last Character
Since PHP supports negative indexing (PHP 7.1+), you can use -1 to access
the last character.
<?php
$str = "World";
echo $str[-1]; // Outputs: d
echo $str[-2]; // Outputs: l
?>
For older PHP versions (before 7.1), use strlen():
<?php
$str = "World";
echo $str[strlen($str) - 1]; // Outputs: d
?>
3. Looping Through a String (Character by Character)
You can loop through a string to access each character.
<?php
$str = "PHP";
for ($i = 0; $i < strlen($str); $i++) {
echo $str[$i] . "\n";
}
?>
4. Modifying a Character in a String
Since strings are mutable, you can modify specific characters.
<?php
$str = "Hello";
$str[0] = "J";
echo $str; // Outputs: Jello
?>
5. Checking if a Character Exists in a String
Using strpos() to check if a character exists:
<?php
$str = "Coding";
if (strpos($str, 'o') == true) {
echo "'o' found in the string.";
} else {
echo "'o' not found.";
}
?>
6. Extracting a Substring
To get part of a string, use substr():
<?php
$str = "Hello, World!";
$part = substr($str, 7, 5);
echo $part; // Outputs: World
?>
Cleaning Strings
 Cleaning strings is essential to ensure data integrity, security, and proper
formatting.
 PHP provides multiple functions to remove unnecessary spaces, escape
characters, and sanitize inputs.
1. Removing Unwanted Spaces
Using trim(), ltrim(), and rtrim()
These functions remove whitespace (spaces, newlines, tabs) from a string.
<?php
$str = " Hello, PHP! ";
echo trim($str); // Outputs: "Hello, PHP!"
echo ltrim($str); // Outputs: "Hello, PHP! "
echo rtrim($str); // Outputs: " Hello, PHP!"
?>
 You can also remove specific characters.
<?php
$str = "---Hello, PHP!---";
echo trim($str, "-"); // Outputs: "Hello, PHP!"
?>
2. Using str_replace()
To remove or replace specific characters:
<?php
$str = "Hello! Welcome to PHP?";
$clean_str = str_replace(["!", "?"], "", $str);
echo $clean_str; // Outputs: "Hello Welcome to PHP"
?>
3. Removing HTML Tags
Using strip_tags()
Removes HTML and PHP tags.
<?php
$html = "<p>Hello <b>PHP</b>!</p>";
echo strip_tags($html); // Outputs: "Hello PHP!"
?>
If you want to allow certain tags:
<?php
echo strip_tags($html, "<b>"); // Outputs: "Hello <b>PHP</b>!"
?>
Encoding and Escaping
 Encoding strings in PHP
 Encoding converts special characters into a format that can be safely stored
or transmitted.
1.1 htmlspecialchars()
Converts special HTML characters to their entity equivalents.
Helps prevent XSS attacks by escaping characters like <, >, &, ", and '.
<?php
$str = "<h1>Welcome to PHP!</h1>";
$encodedStr = htmlspecialchars($str);
echo $encodedStr; // Output: &lt;h1&gt;Welcome to PHP!&lt;/h1&gt;
?>
1.2 htmlentities()
Converts all applicable characters to their HTML entity equivalents.
Unlike htmlspecialchars(), it encodes all characters with HTML equivalents.
<?php
$str = "5 > 3 and 3 < 5";
$encodedStr = htmlentities($str);
echo $encodedStr; // Output: 5 &gt; 3 and 3 &lt; 5
?>
1.3 urlencode()
Converts a string into a format that can be used in a URL by replacing spaces
and special characters with % encoding.
<?php
$str = "Hello PHP!";
$encodedStr = urlencode($str);
echo $encodedStr; // Output: Hello+PHP%21
?>
1.4 base64_encode()
Encodes binary data into a base64 string (commonly used in email and
image encoding).
Used when storing binary data as text.
<?php
$str = "Hello PHP!";
$encodedStr = base64_encode($str);
echo $encodedStr; // Output: SGVsbG8gUEhQIQ==
?>
Escaping
 Escaping ensures that special characters are treated as part of the string rather
than interpreted as code.
 Prevents special characters from breaking things or causing security issues.
1. addslashes()
 Adds a backslash (\) before special characters like ', ", \, and NULL.
<?php
$str = "It's a PHP course";
$escapedStr = addslashes($str);
echo $escapedStr; // Output: It\'s a PHP course
?>
Removing slashes:
<?php
$originalStr = stripslashes($escapedStr);
echo $originalStr; // Output: It's a PHP course
?>
2. strip_tags()
Removes all HTML and PHP tags from a string.
<?php
$str = "<h1>Hello <b>World</b>!</h1>";
$cleanStr = strip_tags($str);
echo $cleanStr; // Output: Hello World!
?>

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)
?>

Using strcmp() (Case-Sensitive Comparison)


Similar to strcasecmp() but case-sensitive.
<?php
echo strcmp("Hello", "hello"); // Output: Negative value (H < h)
?>
Using strncmp() (Compare First N Characters)
 Compares only the first N characters of two strings.
<?php
echo strncmp("HelloWorld", "HelloPHP", 5); // Output: 0 (First 5 characters are
equal)
?>
Manipulating Strings in PHP
 Concatenation(. Operator)
 Changing Case (strtoupper(), strtolower(), ucfirst(), ucwords())
 strtoupper() → Converts to uppercase.
 strtolower() → Converts to lowercase.
 ucfirst() → Capitalizes first letter.
 ucwords() → Capitalizes first letter of each word.
<?php
echo strtoupper("hello world!"); // Output: HELLO WORLD!
echo strtolower("HELLO WORLD!"); // Output: hello world!
echo ucfirst("hello world!"); // Output: Hello world!
echo ucwords("hello world!"); // Output: Hello World!
?>
 Trimming Spaces (trim(), ltrim(), rtrim())
Searching Strings in PHP

 Finding a Substring (strpos(), stripos())


 strpos() → Finds first occurrence (case-sensitive).
 stripos() → Finds first occurrence (case-insensitive).
 Returns position if found, false otherwise.
<?php
$str = "Hello PHP!";
$pos = strpos($str, "PHP");
if ($pos == true) {
echo "Found at position $pos"; // Output: Found at position 6
}
?>
 Checking if a String Contains a Word (str_contains())
 str_contains($string, "word") checks if the string contains a word (PHP 8+).
<?php
echo str_contains("Hello PHP!", "PHP"); // Output: 1 (true)
?>
 Checking Start or End of a String (str_starts_with(), str_ends_with())
 str_starts_with($string, "word") → Checks if a string starts with a given word.
 str_ends_with($string, "word") → Checks if a string ends with a given word.

<?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

 Types of Arrays in PHP


 Indexed Arrays (Numerically indexed)
 Associative Arrays (Key-value pairs)
 Multidimensional Arrays (Arrays inside arrays)
Defining an array

 In PHP, an array is a data structure that can store multiple values in a


single variable.
 PHP provides different ways to define an array.
Using array() function
 $fruits = array("Apple", "Banana", "Orange");
Using Short Array Syntax
 $fruits = ["Apple", "Banana", "Orange"];
 Indexed Arrays
Indexed arrays use numeric indices (starting from 0).
Declaring indexed array
<?php
$fruits = array("Apple", "Banana", "Orange");
$colors = ["Red", "Blue", "Green"];
?>
Accessing indexed array
echo $fruits[0]; // Output: Apple
echo $colors[2]; // Output: Green
Adding Elements
$fruits[] = "Mango"; // Adds "Mango" at the end
array_push($fruits, "Grapes"); // Another way to add
 Looping through an indexed array
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
 Associative Arrays
 Associative arrays use named keys instead of numeric indices.
Declaring Associative array
$student = array(
"name" => "John",
"age" => 22,
"course" => "BIT"
);
Accessing Associative array
echo $student["name"]; // Output: John
echo $student["course"]; // Output: BIT
Adding Elements
$student["email"] = "[email protected]";
 Looping through associative array
foreach ($student as $key => $value) {
echo "$key: $value <br>";
}
Multidimensional Array
 A multidimensional array is an array that contains one or more arrays
as its elements.
 It is useful for storing structured data, like tables or hierarchical data.
 Defining a multidimensional array
$students = [
["Name" => "Alice", "Age" => 21, "Course" => "BIT"],
["Name" => "Bob", "Age" => 23, "Course" => "CS"],
["Name" => "Charlie", "Age" => 20, "Course" => "IT"]
];

// Accessing a specific student's data


echo $students[0]["Name"]; // Output: Alice
echo $students[1]["Age"]; // Output: 23
 Looping through an multidimensional array
foreach ($students as $student) {
echo "Name: " . $student["Name"] . ", Age: " . $student["Age"] . ", Course: " .
$student["Course"] . "<br>";
}
Output:
Name: Alice, Age: 21, Course: BIT
Name: Bob, Age: 23, Course: CS
Name: Charlie, Age: 20, Course: IT
Multidimensional Array with Numeric Indexes
You can also define a multidimensional array without associative keys.
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// Accessing elements
echo $matrix[1][2]; // Output: 6
 Adding and Modifying Data in a Multidimensional Array
$students[] = ["Name" => "David", "Age" => 22, "Course" =>
"AI"];
$students[1]["Course"] = "Software Engineering"; // Changes Bob's
course
Extracting multiple values

 Using list() to Extract Values from an Indexed Array


 The list() function allows assigning multiple values from an array to variables.
$person = ["Alice", 25, "Engineer"];
list($name, $age, $job) = $person;

echo "Name: $name, Age: $age, Job: $job";

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);

echo "Name: $name, Email: $email, Age: $age";

Output:

Name: Bob, Email: [email protected], Age: 30


 Extracting Multiple Values Using foreach (for Multidimensional Arrays)
 For arrays with multiple values, foreach is useful.
$students = [
["Alice", 21, "CS"],
["Bob", 22, "IT"],
["Charlie", 23, "AI"]
];
foreach ($students as list($name, $age, $course)) {
echo "Student: $name, Age: $age, Course: $course <br>";
}
Output:
Student: Alice, Age: 21, Course: CS
Student: Bob, Age: 22, Course: IT
Student: Charlie, Age: 23, Course: AI
Conversion between array and
variables
 Converting Variables to an Array
 Using compact()
 The compact() function creates an associative array from variables. The variable
names become the array keys.
$name = "Alice";
$age = 25;
$city = "New York";

$person = compact("name", "age", "city");

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

You might also like