php unit 2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

Object 3

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.

PHP Array Types


There are 3 types of array in PHP.

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

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

substr(): Returns a part of a string.

<?php
$str = "Hello, world!";
echo substr($str, 0, 5); // Output: Hello
?>

str_replace(): Replaces all occurrences of a search string with a replacement string.

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

Manipulating strings in PHP involves a variety of operations such as concatenation, splitting,


searching, replacing, formatting, and more. Here's a list of some key functions and methods in
PHP that are commonly used for manipulating strings:

1. Concatenation

Concatenation Operator (`.`)**: Joins two strings together.

<?php

$str1 = "Hello";

$str2 = "World";

$result = $str1 . ' ' . $str2; ?> // Result: "Hello World"


2. String Length

strlen(): Returns the length of a string.

<?php

$str = "Hello";

echo strlen($str); // Output: 5

?>

3. Substring:substr()

Returns a part of a string.

<?php

$str = "Hello, world!";

echo substr($str, 0, 5);

?> // Output: Hello

4. Searching

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

<?php

$str = "Hello, world!";

echo strpos($str, "world"); // Output: 7

?>

5. Replacing

str_replace(): Replaces all occurrences of a substring with another substring.

<?php

$str = "Hello, world!";

echo str_replace("world", "PHP", $str); // Output: Hello, PHP!

?>
6. Case Conversion

strtolower(): Converts a string to lowercase.

-strtoupper(): Converts a string to uppercase.

<?php

$str = "Hello";

echo strtolower($str); // Output: hello

echo strtoupper($str); // Output: 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

$str = " Hello ";

echo trim($str); // Output: "Hello"

?>

8. Padding

-str_pad(): Pads a string to a certain length with another string.

<?php

$str = "Hello";

echo str_pad($str, 10, "-"); // Output: "Hello-----"

?>

9. Splitting

explode(): Splits a string into an array by a specified delimiter.

implode() or join() Joins array elements into a string using a specified delimiter.
<?php

$str = "apple,banana,cherry";

$arr = explode(",", $str); // $arr = ["apple", "banana", "cherry"]

echo implode(", ", $arr); // Output: "apple, banana, cherry"

?>

10. Formatting

- sprintf(): Returns a formatted string using placeholders.

<?php

$name = "Alice";

$age = 30;

echo sprintf("Name: %s, Age: %d", $name, $age); // Output: "Name: Alice, Age: 30"

?>

11. Regular Expressions

preg_match(): Performs a regular expression match.

preg_replace(): Performs a regular expression search and replace.

<?php

$str = "Hello, world!";

preg_match("/world/", $str, $matches); // $matches = ["world"]

echo preg_replace("/world/", "PHP", $str); // Output: "Hello, 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");
?>

Get Your Time Zone


If the time you got back from the code is not correct, it's probably because your server is in
another country or set up for a different timezone.
So, if you need the time to be correct according to a specific location, you can set the timezone
you want to use.
The example below sets the timezone to "America/New_York", then outputs the current time in
the specified format:
example:
<?php
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
?>

Create a Date With mktime()


The optional timestamp parameter in the date() function specifies a timestamp. If omitted, the
current date and time will be used (as in the examples above).
The PHP mktime() function returns the Unix timestamp for a date. The Unix timestamp contains
the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time
specified.
Example;
<?php
$d=mktime(11, 14, 54, 8, 12, 2014);
echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>
o/p:Created date is 2014-08-12 11:14:54am

Creating an Object:
Following is an example of how to create object using new operator.

You might also like