PHP Unit 2
PHP Unit 2
2
1
ARRAYS:
PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple
values of similar type in a single variable.
Advantage of PHP Array
Less Code: We don't need to define multiple variables.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
Sorting: We can sort the elements of array.
1.Indexed Array
2.Associative Array
3.Multidimensional Array
PHP Indexed Array
PHP index is represented by number which starts from 0. We can store number, string and object
in the PHP array. All PHP array elements are assigned to an index number by default.
There are two ways to define indexed array:
1st way:
1. $season=array("summer","winter","spring","autumn");
2nd way:
1. $season[0]="summer";
2. $season[1]="winter";
3. $season[2]="spring";
4. $season[3]="autumn";
example program:
<?php
1.$season=array("summer","winter","spring","autumn");
2.echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
3.?>
PHP Associative Array
We can associate name with each array elements in PHP using => symbol.
There are two ways to define associative array:
1st way:
1. $salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
1. $salary["Sonoo"]="350000";
2. $salary["John"]="450000";
3. $salary["Kartik"]="200000";
PHP multidimensional array is also known as array of arrays. It allows you to store tabular data
in an array. PHP multidimensional array can be represented in the form of matrix which is
represented by row * column.
Definition
1. $emp = array
2. (
3. array(1,"sonoo",400000),
4. array(2,"john",500000),
5. array(3,"rahul",300000)
6. );
Array Functions:
1.array_chunk() Function:
The array_chunk() function splits an array into chunks of new arrays.
Syntax: array_chunk(array, size, preserve_key)
Example
Split an array into chunks of two:
<?php
$cars=array("Volvo","BMW","Toyota","Honda","Mercedes","Opel");
print_r(array_chunk($cars,2)); ?>
2.PHP count() function
PHP count() function counts all elements in an array.
example:
<?php
$season=array("summer","winter","spring","autumn");
echo count($season);
?>
3.array_column() Function:
The array_column() function returns the values from a single column in the input array.
Syntax:array_column(array, column_key, index_key)
example;
<?php
// An array that represents a possible record set returned from a database
$a= array(
array(
'id' => 5698,
'first_name' => 'Peter',
'last_name' => 'Griffin',
),
array(
'id' => 4767,
'first_name' => 'Ben',
'last_name' => 'Smith',
),
array(
'id' => 3809,
'first_name' => 'Joe',
'last_name' => 'Doe',
)
);
$last_names=array_column($a, 'last_name');
print_r($last_names);
?>
4.array_combine() Function:
The array_combine() function creates an array by using the elements from one "keys" array
and one "values" array.
Note: Both arrays must have equal number of elements!
Syntax:array_combine(keys, values)
example:
<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
$c=array_combine($fname,$age);
print_r($c);
?>
5.array_count_values() Function;
The array_count_values() function counts all the values of an array.
Syantax:array_count_values(array)
example:
<?php
$a=array("A","Cat","Dog","A","Dog");
print_r(array_count_values($a));
?>
6.array_diff() Function
The array_diff() function compares the values of two (or more) arrays, and returns the
differences.
This function compares the values of two (or more) arrays, and return an array that contains the
entries from array1 that are not present in array2 or array3, etc.
Syantax:array_diff(array1, array2, array3, ...)
example:
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
$result=array_diff($a1,$a2);
print_r($result);
?>
7.array_intersect() Function
The array_intersect() function compares the values of two (or more) arrays, and returns the
matches.
This function compares the values of two or more arrays, and return an array that contains the
entries from array1 that are present in array2, array3, etc.
Syantax;array_intersect(array1, array2, array3, ...)
example:
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
$result=array_intersect($a1,$a2);
print_r($result);
?>
o/p:Array ( [a] => red [b] => green [c] => blue
8.array_merge() Function
The array_merge() function merges one or more arrays into one array.
Tip: You can assign one array to the function, or as many as you like.
Note: If you assign only one array to the array_merge() function, and the keys are integers, the
function returns a new array with integer keys starting at 0 and increases by 1 for each value (See
example below).
syantax:array_merge(array1, array2, array3, ...)
example:
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
9.array_push()
The array_push() function inserts one or more elements to the end of an array.
Tip: You can add one value, or as many as you like.
Note: Even if your array has string keys, your added elements will always have numeric keys
(See example below).
Syantax:array_push(array, value1, value2, ...)
example:<?php
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>
10.array_replace()
The array_replace() function replaces the values of the first array with the values from following
arrays.
Tip: You can assign one array to the function, or as many as you like.
Syantax: array_replace(array1, array2, array3, ...)
example:
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_replace($a1,$a2));
?>
o/p:Array ( [0] => blue [1] => yellow )
11.array_reverse()
The array_reverse() function returns an array in the reverse order.
Syntax:array_reverse(array, preserve)
example:<?php
$a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");
print_r(array_reverse($a));
?>
o/p:Array ( [c] => Toyota [b] => BMW [a] => Volvo )
12.array_search()
The array_search() function search an array for a value and returns the key.
Syantax:array_search(value, array, strict)
example:
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_search("red",$a);
?>
Objects:
Classes are nothing without objects! We can create multiple objects from a class. Each object has
all the properties and methods defined in the class, but they will have different property values.
Objects of a class are created using the new keyword.
Syntax;
objectname=new classname();
example;
class Books {
// Members of class Books
}
// Creating three objects of Books
$physics = new Books;
$maths = new Books;
$chemistry = new Books;
example2;
class myclass{
$prop=”class properties”;
}
$p1=new myclass;
echo $p1-->prop;
o/p:class properties
string:
A string is a sequence of characters, like "Hello world!".
Strings in PHP are surrounded by either double quotation marks, or single quotation marks.
Example: echo "Hello";
echo 'Hello';
You can use double or single quotes, but you should be aware of the differences between the two.
Double quoted strings perform action on special characters.
E.g. when there is a variable in the string, it returns the value of the variable:
Example: $x = "John";
echo "Hello $x";
Types of strings:
• formatting strings
• investigating strings
• manipulating strings
Formatting strings:
simple printf:
printf(“%d%d”,5,6);
o/p:5
6
Type specifications:
float %f
characters %c
binary %b
signed %d
unsigned %u
Octal integer %o
string %s
lowercase %x
Uppercase %X
exponent %e
Example:
print(“%d%f%b”,543.21,543.21,543.21);
o/p:543,543.21,1001101
sign specification;
printf(“%+d”,36); //o/p:+36
printf(“%+d”,-36); //o/p:-36
padding specification:
printf(“%04d”,12); // o/p: 0012
printf(“%04d”,1234); //o/p:1234
printf(“%04d”,12345); //o/p:12345
printf(“%10s”,”hello”); //o/p:-----hello
printf(“%*10s”,”hello”); //o/p:*****hello
printf(“%*-10s”,”hello”); //o/p:hello*****
swapping:
printf(“%2d%1d”,6,10);
o/p:10 6
Investigating strings:
Investigating strings in PHP involves understanding how PHP handles strings, including their
manipulation, concatenation, and various built-in functions for string operations.
strlen(): Returns the length of a string.
<?php
$str = "Hello, world!";
echo strlen($str); // Output: 13
?>
strpos(): Finds the position of the first occurrence of a substring within a string.
<?php
$str = "Hello, world!";
echo strpos($str, "world"); // Output: 7
?>
<?php
$str = "Hello, world!";
echo substr($str, 0, 5); // Output: Hello
?>
<?php
$str = "Hello, world!";
echo str_replace("world", "PHP", $str); // Output: Hello, PHP!
?>
String Comparison
PHP provides various functions (strcmp(), strcasecmp(), strncmp(), etc.) for comparing strings
based on their contents.
<?php
$str1 = "apple";
$str2 = "Apple";
echo strcmp($str1, $str2); // Output: 1 (because 'a' is greater than 'A')
?>
Manipulating strings
1. Concatenation
<?php
$str1 = "Hello";
$str2 = "World";
<?php
$str = "Hello";
?>
3. Substring:substr()
<?php
4. Searching
<?php
?>
5. Replacing
<?php
?>
6. Case Conversion
<?php
$str = "Hello";
?>
7. Trimming
- **trim()**: Removes whitespace or other specified characters from the beginning and end of a
string.
- **ltrim()**: Removes whitespace or other specified characters from the beginning of a string.
- **rtrim()**: Removes whitespace or other specified characters from the end of a string.
<?php
?>
8. Padding
<?php
$str = "Hello";
?>
9. Splitting
implode() or join() Joins array elements into a string using a specified delimiter.
<?php
$str = "apple,banana,cherry";
?>
10. Formatting
<?php
$name = "Alice";
$age = 30;
echo sprintf("Name: %s, Age: %d", $name, $age); // Output: "Name: Alice, Age: 30"
?>
<?php
?>
These are some of the key functions and methods available in PHP for manipulating strings.
Understanding and using these functions effectively can greatly enhance your ability to work
with strings in PHP applications.
Date and Time:
The PHP date() function is used to format a date and/or a time.
Get a Date:
The required format parameter of the date() function specifies how to format the date (or time).
Here are some characters that are commonly used for dates:
•d - Represents the day of the month (01 to 31)
•m - Represents a month (01 to 12)
•Y - Represents a year (in four digits)
•l (lowercase 'L') - Represents the day of the week
Other characters, like"/", ".", or "-" can also be inserted between the characters to add additional
formatting.
The example below formats today's date in three different ways:
example:
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
Get a Time:
Here are some characters that are commonly used for times:
•H - 24-hour format of an hour (00 to 23)
•h - 12-hour format of an hour with leading zeros (01 to 12)
•i - Minutes with leading zeros (00 to 59)
•s - Seconds with leading zeros (00 to 59)
•a - Lowercase Ante meridiem and Post meridiem (am or pm)
The example below outputs the current time in the specified format:
<?php
echo "The time is " . date("h:i:sa");
?>
Creating an Object:
Following is an example of how to create object using new operator.