Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

PHP Unit2 Notes

Php unit2 notes

Uploaded by

sankarkumarkvdc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

PHP Unit2 Notes

Php unit2 notes

Uploaded by

sankarkumarkvdc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Unit-2

(1)Arrays (2) Objects (3)Strings (4)Date and


Time functions

Arrays
- In PHP, Arrays are nothing but list of items and Items may be of similar datatypes or
different datatypes under a single name.

- We can create arrays in 2 ways.

- First, By using array() function.

Ex:-

$Items=array(1,"Sankar",98.8,true,none);

(or)

- second, By using array operator i.e [].

Ex:-

$items=[1,"sankar",98.8,true,none];

- Here, Each Item/Element in an array is called index of an array and the index starts with 0.

- First element is represeted with $items[0].

Second element is represented with $items[1] and so on....

- To print each element of an array , we use print_r() function.

- To iterate over each element of an array, we use foreach loop.

Ex:-

<?php

$items=[1,"sankar",98.8,true,null];

print_r($items);

?>

Ex:-

<?php
$items=[1,"sankar",98.8,true,null];

foreach($items as $item)

echo $item;

echo "<br>";

?>

- Arrays are of 3 types

1. Numbered Array/Index array

2. Associative array

3. Multidimentional array.

1. Numbered Array/ Index array:

The array which contains number as index is called Index array and the index starts from 0.

Ex:-

<?php

$items=[1,"sankar",98.8,true,null];

print_r($items);

?>

Ex:-

<?php

$items=[1,"sankar",98.8,true,null];

foreach($items as $item)

echo $item;

echo "<br>";

}
?>

2. Associative array:

- In associative array, instead of index if we represent index as key and value. This become an
associative array.

- The key and value must be separated with =>

- The Left hand side of => is called key and Right hand side of => is called value.

key=>value

- A string much be enclosed with single quotes or double quotes in place of either key or
value.

Ex:-

1)

<?php

$person=[

"f_n"=>"Brad",

'l_n'=>'Traversy',

'email'=>'brad@gmail.com'

];

echo $person["f_n"];

?>

2)

<?php

$sal=[

"rahul"=>20000,

"rajat"=>12000,

"sunny"=>10000

];
echo $sal['rahul'];

?>

3)

<?php

$colors=[

1=>'red',

4=>'blue',

6=>'green'

];

echo $colors[4];

?>

MultiDimensional array:

- An array can hold an array as values that makes a MultiDimensional array.

or

-an array of arrays is also a Multidimensional array.

Ex:-

1)

<?php

$people=[

'f_n'=>'Brad',

'l_n'=>'Traversy',

'email'=>'brad@gmail.com'

],

'f_n'=>'John',
'l_n'=>'Doe',

'email'=>'John@gmail.com'

],

"f_n"=>'Jane',

'l_n'=>'Doe',

'email'=>'Jane@gmail.com'

];

echo $people[1]['email'];

?>

2)

<?php

$cars=[

"expensive"=>["Audi","Mercedes","BMW"],

"inexpensive"=>["volvo","Ford","Toyota"]

];

echo $cars['expensive'][0];

?>

3)

<?php

$pls=[

'php'=>[

'creator'=>'Rasmus Lerdorf',

'extension'=>'.php',

'versions'=>[
['version'=>8,'releasedate'=>'Nov26,2016'],

['version'=>7.4,'releasedate'=>'Nov28,2019'],

],

'python'=>[

'creator'=>'Guido Van Rossum',

'extension'=>'.py',

'versions'=>[

['version'=>3.9,'releasedate'=>'oct25,2020'],

['version'=>3.8,'releasedate'=>'oct14,2019'],

],

],

],

];

echo $pls['php']['extension'];

echo "<br>";

echo $pls['php']['versions'][0]['releasedate'];

?>

Array functions:

In PHP, Array functions allows you to interact with and manipulate arrays in various ways.

1. count() function:
This function returns the count of number of elements in an array.

<?php

$fruits=['apple','orange','pear'];

echo count($fruits);
?>

2.sizeof() function: Same as count() function

<?php

$fruits=['apple','orange','pear'];

echo sizeof($fruits);

?>

3.in_array() function:

The function searches an element is present in an array. If present it returns true,otherwise


it returns false.

<?php

$fruits=['apple','orange','pear'];

var_dump(in_array('apple',$fruits)); // true

?>

4. Adding into an array:

i) array_push() function: The function will add the element at the end of an array.

<?php

$fruits=['apple','orange','pear'];

array_push($fruits,'blueberry','strawberry');

print_r($fruits);

ii) array_unshift() function: This function will add the element at the beginning of an array.

<?php

$fruits=['apple','orange','pear'];

array_unshift($fruits,'mango');
print_r($fruits);

?>

5. To remove from an array:

i) array_pop() function: This function will remove an element at the end of an array.

<?php

$fruits=['apple','orange','pear'];

array_pop($fruits);

print_r($fruits);

?>

ii) array_shift() function: This function will remove an element from the beginning of an
array.

<?php

$fruits=['apple','orange','pear'];

array_shift($fruits);

print_r($fruits);

?>

Note: Re-index of keys happens here.

iii) unset() function:

This function will remove an element at the specific index.

<?php

$fruits=['apple','orange','pear'];

unset($fruits[2]);

print_r($fruits);

?>

Note: Here, Re-index will not happen.


6. array_chunk() function:

This function will split the array into 2 parts.

<?php

$fruits=['apple','orange','pear'];

$chuncked_array=array_chunk($fruits,2);

print_r($chuncked_array);

7. array_merge() function:

This function will merge 2 arrays into a single array.

<?php

$arr1=[1,2,3];

$arr2=[4,5,6];

$arr3=array_merge($arr1,$arr2);

print_r($arr3);

?>

8. array_combine() function:

This function will combine 2 arrays in such a way that first array elements as keys and
second array elements as values in the newly combined array.

<?php

$a=['green','red','yellow'];

$b=['avacado','apple','banana'];

$c=array_combine($a,$b);

print_r($c);

?>
9. array_keys() function:

This function will return only keys of an array.

<?php

$c=['green'=>'avacado','red'=>'apple','yellow'=>'banana'];

$keys=array_keys($c);

print_r($keys);

?>

10. array_flip() function:

This function will interchange key as values and values as keys.

<?php

$c=['green'=>'avacado','red'=>'apple','yellow'=>'banana'];

$flipped=array_flip($c);

print_r($flipped);

?>

11. range() function:

This function will give range of values in the form of an array.

<?php

$numbers=range(1,20);

print_r($numbers);

?>
Working with Objects:
PHP supports Object oriented Programming.

Object:

- Objects are real - world entity like a person, a car

- Object is an instance of a class.

- Each Object has some properties and some functionalities.

Class:

- A class is a Blue print or a template of an object.

- A class is an abstract but Objects are real.

Encapsulation: Wrapping up of data and information under a single unit.

Data abstraction: Providing only essential information about the data and hiding the
background details or implementation.

Creating classes and Objects in php:

Class creation:

- we can create a class by using class keyword followed by classname.

- A class contains both properties(Variables) and behaviour(methods).

- The following is the syntax.

class classname

public $property1;

private $property2;

protected $property3;

public function method1()

}
Object creation:

- we can create an object by using new keyword.

- The following is the syntax.

$object=new classsname();

Ex:-

<?php

class Myclass

public $greeting="Have a Nice Day";

public function hello()

echo $this->greeting;

$obj=new Myclass();

$obj->hello();

?>

output:

Have a Nice Day


Working with Strings:
String: A string is group of characters that are enclosed with either single quotes or double
quotes.

- when you enclose with single quotes, variable values will not be replaced.

- When you enclose with double quotes, variable values will be replaced.

<?php

$name="sankar";

echo 'My name is $name';

echo "<br>";

echo "My name is $name";

?>

Formatting Strings with php

- Formatting Strings means converting data between different formats.

- PHP has given the following functions to format the strings.

1)printf()

2)sprintf()

1) printf() function:

- This function is used to print text in a function on to the screen.

- printf() function takes two arguments. One is format control string and other is data to be
displayed.

- format control string specifies which type of data to be displayed.

format cotrol string Description

%d To display Integers

%b To display integer as binary

%c To display integer as ASCII character.


%f To display integer as Floatingpoint number.

%o To display integer as Octal Number.

%s To display Strings.

%x To display Integer as Lower case HexaDecimal Number

%X To display Integer as Upper case HexaDecemal Number.

Ex:-

<?php

$number=543;

printf("Integer number %d<br>",$number);

printf("Binary Number %b<br>",$number);

printf("Character %c<br>",$number);

printf("Floating Number %f<br>",$number);

printf("Octal Number %o<br>",$number);

printf("String is %s<br>",$number);

printf("Hexa decimal in lower case %x<br>",$number);

printf("Hexa decimal in Upper case %X<br>",$number);

?>

padding Output with padding specifier

- we can also display data by padding (Leading characters with either 0's or whitespaces or
any character).

- The padding specifer should be written after the percentage sign.

Ex:-

<?

printf("%04d<br>",36);

printf("%015d<br>",36);
printf("%'x4d",36);

?>

Specifying a Field Width:

- It specifies the space within which your output should sit.

- A field width specified by an Integer that should be placed after the % sign and followed by
a conversion character.

Ex:-

<?php

echo "<pre>";

printf("%20s<br>","Books");

printf("%20s","CDs");

echo "</pre>";

?>

Precision specifier:

- It is used to determine the number of decimal places to be displaced.

- precision specifier should directly follow the % sign and followed by conversion character.

Ex:-

<?php

printf("%.2f",5.33333333);

?>

2) sprintf() function

- printf() function is used to display output to the browser.

- But sprintf() function is used to store the output into a variable for later use.
Ex:-

<?php

$price=sprintf("%.2f",21.3344);

echo $price;

?>

Investigating Strings in PHP

- String is nothing but a group of characters that are enclosed with either single quotes or
double quotes.

- Strings arrives from many sources including user input,databases, files, and webpages...

- Before you begin work with data from an external source, you often need to find out more
about the data.

For that PHP provides following functions.

1) strlen()

2)strstr()

3)strpos()

4)substr()

5)strtok()

1)strlen() function

- This function is used to find number of characters in a Strinng

syntax:

strlen($string)

Ex:-

<?php

$name1="srikanth";

echo(strlen($name1));
?>

2)strstr() function:

- This function is used to find a substring with in a string.

syntax:

strstr($originalstring,"substring");

Ex:-

1)

<?php

var_dump(strstr($name1,"ka"));

?>

2)

<?php

$email="user@example.com";

$domain=strstr($email,'@',true);

echo $domain;

?>

3) strpos() function:

This function is used to find the position of substring with in a string

syntax:

strpos($originalstring,"string");

Ex:-

<?php

$string="srikanth";

$position=strpos($string,"ka");

echo $position;
?>

4) substr() function:

- This function is used to extract a part of a string.

syntax:

substr($originalstring,startingindex,endingindex)

Ex:-

<?php

$text="srikanth";

echo substr($text,3);

echo "<br>";

echo substr($text,3,2);

?>

5)strtok() function:

- This function is used to divide/tokenize a string into word by word.

- This function requires two arguments. The string to be tokenized and delimiter.

syntax:

strtok($string, delimiter)

Ex:-

<?php

$text1="srikanth yaramach";

$token=strtok($text1," ");

while($token!==false)

echo $token . "<br>";

$token=strtok(" ");
}

?>

<?php

$string = "apple,banana,cherry, date";

$delimiters = ",";

$token = strtok($string, $delimiters);

while ($token !== false) {

echo $token . "<br>";

$token = strtok($delimiters);

?>

Manipulating Strings in PHP

- String is nothing but a group of characters which are enclosed by either single quotes or
double quotes.

- Manipulating strings is nothing but to apply some changes to the string.

- PHP provides the following functions for Manipulation.

1)trim()

2)ltrim(),rtrim()

3)strip_tags()

4)substr_replace()

5)str_replace()

6)strtolower()

7)strtoupper()
8)wordwrap()

9)nl2br()

10)explode()

trim() function:

- This function is used to remove white spaces before and after the String.

Syntax:

trim($string)

Ex:

<?php

$name=" srikanth yaramachu ";

echo trim($name);

?>

ltrim() function:

- This function is used to remove white spaces before the string.

syntax:

ltrim($string)

Ex:

<?php

$name=" Srikanth yaramachu";

echo ltrim($name);

?>

rtrim() function:

- This function will remove white spaces after the String.

syntax:

rtrim($string);
Ex:-

<?php

$name="Srikanth yaramachu ";

echo rtrim($name);

?>

strip_tags() function:

- This function will remove strip(remove) the HTML and PHP tags to string.

syntax:

strip_tags($name)

Ex:-

<?php

$name="<br> srikanth yaramachu </br>";

echo strip_tags($name);

?>

substr_replace() function:

- This function is used to replace a substring with in a String.

syntax:

substr_replace($string,"substring",starting index,ending index);

Ex:-

<?php

$name="srikanth";

echo substr_replace($name,"bzc",3,2);

?>

str_replace() function:

- This function is used to replace all instances of a given string with another string.
syntax:

str_replace("existing","replace",$string);

Ex:-

<?php

$string="<h1>The 2010 Guide to all things good 2010 in the world </h1>";

echo str_replace("2010","2012",$string);

?>

strtolower() function

- This function is used to convert Upper case characters of a string into Lower case.

syntax:

strtolower($string);

Ex:-

<?php

$string="SRIKANTH";

echo strtolower($string);

?>

strtoupper() function

- This function is used to convert Lower case characters of a string into Upper case.

syntax:

strtoupper($string)

Ex:-

<?php

$string="srikanth";

echo strtoupper($string);
?>

wordwrap() function

- This function is used to break lines into a columns.

syntax:

wordwrap($string)

Ex:-

<?php

$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sit amet accumsan
arcu.";

$wrapped = wordwrap($text, 20, "<br />\n");

echo $wrapped;

?>

nl2br() function

This function converts every new line into an HTML break.

syntax:

nl2br($string);

Ex:-

<?php

$string="firstline.\nsecond line.\nThird line.";

echo nl2br($string);

?>

explode() function

- This function is used to break the string into an array.

- It requires 2 arguments. They are delimiter string and source string.

syntax:

explode(delimiter string,$sourcestring);
Ex:-

<?php

$startdate="2024-07-21";

$datearray=explode("-",$startdate);

foreach($datearray as $e)

echo $e . "<br>";

?>

Date and Time Functions


- PHP provides a robust set of functions for working with dates and times.

- These functions allow you to get the current date and time, format dates and times, and
perform various calculations with date and time values.

Here are some of the key functions and classes:

-- Basic Functions:

date(), time()

-- Formatting Functions:

date()

-- Creation and Parsing Functions:

mktime(), strtotime()

date() function:

- The date() function formats a local date and time, and returns the formatted date string.

syntax:

date(format,timestamp);

Format Characters:

Y: 4-digit year (e.g., 2024)

m: 2-digit month (e.g., 07)

d: 2-digit day of the month (e.g., 20)

H: 2-digit hour in 24-hour format (e.g., 15)

i: 2-digit minute (e.g., 30)

s: 2-digit second (e.g., 45)

a: am/pm in lowercase

A: AM/PM in Uppercase

g:Hours(12 hours format-Non leading zeros)


<?php

echo date('Y-m-d H:i:s'); // Outputs: current date and time in 'YYYY-MM-DD HH:MM:SS'
format

?>

time() function:

- The time() function returns the current Unix timestamp, which is the number of seconds
since January 1 1970 00:00:00 GMT.

<?php

echo time(); // Outputs: current Unix timestamp (e.g., 1700456845)

$currenttime=time();

echo date('d/m/Y g:ia',$currenttime) . "<br>";

echo date('d/m/Y g:ia', $currenttime + 5*24*60*60);

?>

Creating Date and Time Values

mktime() function:

- The mktime() function returns the Unix timestamp for a date.

- Parameters: mktime(hour, minute, second, month, day, year)

<?php

echo mktime(15, 30, 0, 7, 20, 2024); // Outputs: Unix timestamp for July 20, 2024 15:30:00

echo date('d/m/Y g:ia',mktime(15,30,0,7,20,2024)) . "<br>";

?>

strtotime() function:
- The strtotime() function parses an English textual datetime description into a Unix
timestamp.

<?php

echo strtotime('next Monday'); // Outputs: Unix timestamp for next Monday

echo date('d/m/Y g:ia',strtotime('next sunday')) . "<br>";

?>

You might also like