0% found this document useful (0 votes)
36 views16 pages

BCA PHP Unit2

This document provides a comprehensive overview of PHP arrays, including their types (indexed, associative, and multidimensional), syntax, benefits, and common use cases. It also covers array manipulation functions, string manipulation, formatting, and comparison functions in PHP. The document serves as a guide for effectively using arrays and strings in PHP programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views16 pages

BCA PHP Unit2

This document provides a comprehensive overview of PHP arrays, including their types (indexed, associative, and multidimensional), syntax, benefits, and common use cases. It also covers array manipulation functions, string manipulation, formatting, and comparison functions in PHP. The document serves as a guide for effectively using arrays and strings in PHP programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

PHP Arrays

Arrays are one of the most important data structures in PHP. They allow you to store multiple
values in a single variable, which is extremely useful when dealing with lists or grouped data.

An array is a special variable that can hold more than one value at a time. It can store a list of
items (numbers, strings, objects, even other arrays).

Syntax:

$array_name = array(value1, value2, value3, ...);

Modern Syntax (PHP 5.4+):

$array_name = [value1, value2, value3];

Array Declaration:
$colors = array("Red", "Green", "Blue");

Accessing Array Elements:


echo $colors[0]; // Output: Red

✅ Benefits of Using Arrays


 Store multiple values in a single variable.
 Easily loop through values using loops.
 Organize data (key-value pairs or indexed).
 Easier to manage related information (like student data, product list, etc.)

✅ Common Use Cases


 Managing form inputs
 Storing database results
 Handling tabular data
 Configuring site settings
 Working with JSON and APIs

Types of Arrays in PHP


1.Indexed Arrays (Numeric Index)
 The index is automatically assigned (starts from 0).
 Used when data has no specific key.

Syntax:

$colors = array("Red", "Green", "Blue");

Example:

$fruits = ["Apple", "Banana", "Mango"];


echo $fruits[1]; // Output: Banana

Using Loop:

foreach ($fruits as $fruit) {


echo $fruit . "<br>";
}

2.Associative Arrays

 Each element is assigned a user-defined key.


 Used when you want to associate meaningful keys with values.

Syntax:

$age = array("John" => 25, "Alice" => 22, "Bob" => 30);

Example:

echo "Alice is " . $age["Alice"] . " years old.";

Using foreach loop:

foreach ($age as $name => $value) {


echo "$name is $value years old.<br>";
}

3.Multidimensional Arrays

 Arrays within arrays.


 Used for matrix-type or tabular data.

Syntax:

$students = [
["John", 85, 90],
["Alice", 78, 88],
["Bob", 92, 79]
];
Accessing:

echo $students[0][0]; // Output: John


echo $students[1][1]; // Output: 78

Using nested loops:

for ($i = 0; $i < count($students); $i++) {


for ($j = 0; $j < count($students[$i]); $j++) {
echo $students[$i][$j] . " ";
}
echo "<br>";
}

Array Operators
PHP allows the use of operators with arrays:

Operator Name Description


+ Union Combines arrays (keys from left are preserved)
== Equality Returns true if both arrays have same key/value pairs
=== Identity Returns true if same key/value and same order
!= or <> Inequality Returns true if arrays are not equal
!== Non-identity Returns true if not identical

Example:

$a = ["a" => 1, "b" => 2];


$b = ["b" => 3, "c" => 4];
$c = $a + $b; // Union
print_r($c); // Array ( [a] => 1 [b] => 2 [c] => 4 )

✅ Array Manipulation Functions in PHP


Below are some of the most commonly used array functions, their purpose, and simple
examples:

1. count() – Count total elements


$nums = array(10, 20, 30);
echo count($nums); // Output: 3

2. array_merge() – Merge two or more arrays


$a = array("Red", "Green");
$b = array("Blue", "Yellow");
$c = array_merge($a, $b);
print_r($c);
// Output: Array ( [0] => Red [1] => Green [2] => Blue [3] => Yellow )

3. array_push() – Add item(s) to end


$colors = array("Red", "Green");
array_push($colors, "Blue", "Yellow");
print_r($colors);

4. array_pop() – Remove last item


$colors = array("Red", "Green", "Blue");
array_pop($colors);
print_r($colors); // Output: Red, Green

5. array_shift() – Remove first item


$colors = array("Red", "Green", "Blue");
array_shift($colors);
print_r($colors); // Output: Green, Blue

6. array_unshift() – Add item(s) to beginning


$colors = array("Green", "Blue");
array_unshift($colors, "Red");
print_r($colors); // Output: Red, Green, Blue

7. in_array() – Check if value exists


$names = array("Ravi", "John", "Anil");
if (in_array("John", $names)) {
echo "Found";
} else {
echo "Not Found";
}

8. array_key_exists() – Check if key exists


$person = array("name" => "Ravi", "age" => 25);
if (array_key_exists("age", $person)) {
echo "Key exists!";
}

9. array_keys() – Get all keys


$person = array("name" => "Ravi", "age" => 25);
print_r(array_keys($person));
// Output: Array ( [0] => name [1] => age )
10. array_values() – Get all values
$person = array("name" => "Ravi", "age" => 25);
print_r(array_values($person));
// Output: Array ( [0] => Ravi [1] => 25 )

11. sort() – Sort array (ascending)


$nums = array(40, 10, 30, 20);
sort($nums);
print_r($nums); // 10, 20, 30, 40

12. rsort() – Reverse sort


$nums = array(40, 10, 30, 20);
rsort($nums);
print_r($nums); // 40, 30, 20, 10

13. asort() – Sort associative array by value


$marks = array("John" => 70, "Ravi" => 90);
asort($marks);
print_r($marks);

14. ksort() – Sort associative array by key


$marks = array("John" => 70, "Ravi" => 90);
ksort($marks);
print_r($marks);

15. array_reverse() – Reverse the array


$nums = array(1, 2, 3, 4);
print_r(array_reverse($nums)); // 4, 3, 2, 1

16. array_slice() – Extract part of an array


$colors = array("Red", "Green", "Blue", "Yellow");
print_r(array_slice($colors, 1, 2)); // Green, Blue

17. array_splice() – Remove/replace elements


$colors = array("Red", "Green", "Blue", "Yellow");
array_splice($colors, 1, 2);
print_r($colors); // Output: Red, Yellow
PHP String Manipulation and Regular
Expressions
1. String Basics
Definition:

A string is a sequence of characters, such as letters, numbers, and symbols, enclosed in quotes.

Syntax:
$string1 = "Hello World!";
$string2 = 'PHP is awesome!';

Notes:

 Strings can be defined using single quotes ('') or double quotes ("").
 Double quotes allow variable interpolation and escape sequences (like \n).
 PHP has rich built-in functions to work with strings.

Example:
$name = "John";
echo "Hello, $name!"; // Output: Hello, John!

2. Formatting Strings in PHP


Formatting strings is a key task in programming when we want to control how numbers, text, or
other data is displayed. PHP provides several functions to help format strings, especially for
outputting nicely formatted values like currency, percentages, or fixed-width values.

1. printf() Function

The printf() function is used to output a formatted string. It writes a formatted string directly
to the output (browser/console).

Syntax:
printf(format_string, arg1, arg2, ...);

Parameters:

 format_string: A string that contains placeholders (format specifiers).


 arg1, arg2...: Values to be inserted into placeholders.
Common Format Specifiers:
Format Description

%s String

%d Integer (decimal number)

%f Floating point number

%.2f Floating point with 2 decimals

%x Hexadecimal

%b Binary

%c ASCII Character

Example:
$price = 49.95;
printf("The price is \$%.2f", $price); // Output: The price is $49.95
$quantity = 5;
$item = "Apples";
$rate = 10.5;
$total = $quantity * $rate;

printf("Item: %s\nQuantity: %d\nRate: %.2f\nTotal: %.2f", $item, $quantity,


$rate, $total);
// Output:
// Item: Apples
// Quantity: 5
// Rate: 10.50
// Total: 52.50

2. sprintf() Function

sprintf() works the same as printf(), but instead of displaying the output, it returns the
formatted string.

Syntax:
$output = sprintf(format_string, arg1, arg2, ...);

Example:
$name = "Aneel";
$score = 95.5;
$formatted = sprintf("Student %s scored %.1f%%", $name, $score);
echo $formatted;
// Output: Student Aneel scored 95.5%
Useful when you want to store the formatted string in a variable or concatenate it later.

3. number_format() Function

number_format() formats a number with grouped thousands, decimal places, etc. It’s mainly
used for currency and readable numeric output.

Syntax:
number_format(number, decimals, decimal_separator, thousand_separator);

Parameters:

 number – The input number.


 decimals (optional) – Number of decimal points.
 decimal_separator (optional) – The symbol to use for decimals.
 thousand_separator (optional) – The symbol to use for thousands.

Examples:
$number = 1234567.891;

echo number_format($number);
// Output: 1,234,568 (rounded to integer)

echo number_format($number, 2);


// Output: 1,234,567.89

echo number_format($number, 2, ',', ' ');


// Output: 1 234 567,89 (custom separators)
$salary = 1000000.50;
echo "Annual Salary: ₹" . number_format($salary, 2);
// Output: Annual Salary: ₹1,000,000.50

Real-Life Use Case:


$product = "Laptop";
$price = 79999.995;

echo sprintf("Buy this %s for just ₹%s!", $product, number_format($price,


2));
// Output: Buy this Laptop for just ₹79,999.99!

✅ 3. Joining and Splitting Strings with String Functions


Manipulating strings often involves joining an array of words into a sentence or splitting a
sentence into individual words or characters. PHP provides several built-in functions for these
tasks.
A. Joining Strings

implode() joins array elements into a single string using a specified separator.

Syntax:
implode(separator, array);

 separator: String inserted between each array element.


 array: The array of strings to join.

If the separator is not specified, PHP uses an empty string "" as the default.

Example 1: Joining with space


$words = ["PHP", "is", "fun"];
echo implode(" ", $words);
// Output: PHP is fun

Example 2: Joining with comma


$items = ["apple", "banana", "cherry"];
$csv = implode(",", $items);
echo $csv;
// Output: apple,banana,cherry

Example 3: Joining without separator


$letters = ['H', 'E', 'L', 'L', 'O'];
echo implode("", $letters);
// Output: HELLO

B. Splitting Strings

explode() splits a string into an array using a specified delimiter.

Syntax:
explode(delimiter, string, [limit]);

 delimiter: The character(s) to split by.


 string: The input string to split.
 limit (optional): Max number of elements returned.

Example 1: Splitting comma-separated string


$text = "apple,banana,grape";
$fruits = explode(",", $text);
print_r($fruits);
// Output:
// Array ( [0] => apple [1] => banana [2] => grape )

Example 2: Limit number of splits


$data = "2025-07-29-India";
$parts = explode("-", $data, 3);
print_r($parts);
// Output: Array ( [0] => 2025 [1] => 07 [2] => 29-India )

C. Other Useful Functions

✅str_split()

Splits a string into individual characters or chunks of specified length.

Syntax:
str_split(string, [length]);

 length is optional. Default is 1 (one character per array element).

Example 1: Split into characters


$text = "HELLO";
print_r(str_split($text));
// Output: Array ( [0] => H [1] => E [2] => L [3] => L [4] => O )

Example 2: Split into chunks of 2


$text = "123456";
print_r(str_split($text, 2));
// Output: Array ( [0] => 12 [1] => 34 [2] => 56 )

✅chunk_split()

Inserts a separator after every chunk of specified length in a string.

Syntax:
chunk_split(string, chunk_length, end_string);

 chunk_length: Number of characters in each chunk (default is 76).


 end_string: What to insert after each chunk (default is \r\n).

Example 1: Split into chunks of 3 with dashes


$text = "ABCDEFGHI";
echo chunk_split($text, 3, "-");
// Output: ABC-DEF-GHI-

Example 2: Split into 2-character chunks with space


$text = "123456";
echo chunk_split($text, 2, " ");
// Output: 12 34 56
Real-World Example:
// Convert CSV line to array, then back to string
$csv = "red,green,blue";
$colors = explode(",", $csv);
echo implode(" - ", $colors); // Output: red - green - blue

✅ 4. Comparing Strings in PHP


In PHP, string comparison is often needed to sort data, check for equality, or validate user
input. PHP provides built-in functions to compare strings either case-sensitively or case-
insensitively.

A. strcmp() – Case-Sensitive Comparison

Compares two strings character by character and is case-sensitive.


Returns:

 0 if both strings are equal


 < 0 if first string is less than second
 > 0 if first string is greater than second

Syntax:
strcmp(string1, string2);

Example 1:
echo strcmp("apple", "banana");
// Output: -1 (because "apple" < "banana" alphabetically)

Example 2:
echo strcmp("Hello", "Hello");
// Output: 0 (exactly the same)

Example 3:
echo strcmp("Zoo", "apple");
// Output: >0 (Z > a)

B. strcasecmp() – Case-Insensitive Comparison

Compares two strings without considering case.


Returns:

 0 if strings are equal ignoring case


 < 0 if first is less than second
 > 0 if first is greater than second
Syntax:
strcasecmp(string1, string2);

Example 1:
echo strcasecmp("Hello", "hello");
// Output: 0 (they are equal if case is ignored)

Example 2:
echo strcasecmp("apple", "Banana");
// Output: <0 ("apple" < "banana" ignoring case)

Example 3:
echo strcasecmp("Zebra", "ant");
// Output: >0

C. strncmp() – Compare First N Characters (Case-Sensitive)

Compares the first N characters of two strings, case-sensitive.


Returns:

 0 if the first N characters are equal


 < 0 if first < second
 > 0 if first > second

Syntax:
strncmp(string1, string2, length);

Example 1:
echo strncmp("application", "apple", 3);
// Output: 0 (first 3 characters are "app")

Example 2:
echo strncmp("application", "banana", 5);
// Output: <0 ("appli" < "banan")

Example 3:
echo strncmp("PHPDeveloper", "PHPMailer", 4);
// Output: 0 ("PHPD" vs "PHPM" — not equal, so >0)

Real-Life Example: Username Validation


$input = "Admin";
$stored = "admin";

if (strcasecmp($input, $stored) == 0) {
echo "Welcome back!";
} else {
echo "Invalid username.";
}
// Output: Welcome back! (ignores case)
5. Matching and Replacing Substrings in PHP
In string processing, searching for substrings and replacing specific content is a common task.
PHP provides powerful string functions to perform such operations efficiently.

1. strpos() – Find Position of First Occurrence

Finds the position (index) of the first occurrence of a substring in a string.

Key Points:

 Case-sensitive.
 Returns the zero-based index (starting from 0).
 Returns false if the substring is not found.

Syntax:
strpos(string $haystack, string $needle, int $offset = 0): int|false

Examples:
$text = "Hello World";
echo strpos($text, "World"); // Output: 6
$text = "Programming is fun.";
echo strpos($text, "m"); // Output: 6 (first 'm')
$text = "Self Made";
$pos = strpos($text, "z");
var_dump($pos); // Output: bool(false)

Used when you need to check if a word/character is present and where it appears.

2. strrpos() – Find Position of Last Occurrence

Finds the position of the last occurrence of a substring.

Key Points:

 Case-sensitive.
 Returns the last match index.
 Returns false if not found.

Syntax:
strrpos(string $haystack, string $needle, int $offset = 0): int|false

Examples:
$text = "banana";
echo strrpos($text, "a"); // Output: 5
$text = "PHP is a scripting language";
echo strrpos($text, "s"); // Output: 15
3. str_replace() – Replace All Occurrences of a Substring

Replaces all instances of a specific substring with another substring.

Key Points:

 Case-sensitive.
 Works with arrays as well.
 Returns a new string (original string remains unchanged).

Syntax:
str_replace(mixed $search, mixed $replace, mixed $subject, int &$count =
null): string

Examples:
$text = "Hello World";
$newText = str_replace("World", "PHP", $text);
echo $newText; // Output: Hello PHP
$sentence = "The red ball is red.";
echo str_replace("red", "blue", $sentence);
// Output: The blue ball is blue.
// Replace multiple words using arrays
$words = ["apple", "banana"];
$replace = ["mango", "grape"];
$sentence = "I like apple and banana.";
echo str_replace($words, $replace, $sentence);
// Output: I like mango and grape.

4. substr_replace() – Replace Part of a String

Replaces a portion of a string with another string, starting and optionally ending at specific
positions.

Key Points:

 More control over which part of string is replaced.


 You can replace from start, middle, or end.
 You can even insert new content.

Syntax:
substr_replace(string $string, string $replacement, int $start, int $length =
null): string

Examples:
$text = "Hello World";
echo substr_replace($text, "PHP", 6);
// Output: Hello PHP
$text = "1234567890";
echo substr_replace($text, "---", 3, 4);
// Output: 123---890
// Inserting without removing
echo substr_replace("abcdef", "123", 2, 0);
// Output: ab123cdef

6. Introducing Regular Expressions


Definition:

A Regular Expression (regex) is a pattern used to match character combinations in strings.

Functions:

 preg_match() – Check if pattern matches


 preg_match_all() – Match all occurrences
 preg_replace() – Replace using pattern
 preg_split() – Split using pattern

Syntax:
preg_match("/pattern/", $string);

Pattern Delimiters:

 Commonly /pattern/
 Special characters: ^, $, ., *, +, ?, [], (), |

Example:
$string = "abc123";
if (preg_match("/[0-9]+/", $string)) {
echo "Numbers found!";
}

7. Find, Replace, Splitting in Regular Expressions


preg_match():

Find if pattern exists

$text = "Welcome123";
if (preg_match("/\d+/",$text)) {
echo "Digits found!";
}
preg_replace():

Replace pattern

$text = "I like cats.";


echo preg_replace("/cats/", "dogs", $text); // Output: I like dogs.

preg_split():

Split string by pattern

$data = "one,two;three|four";
$parts = preg_split("/[,;|]/", $data);
print_r($parts);

You might also like