PHP Unit2 Notes
PHP Unit2 Notes
Arrays
- In PHP, Arrays are nothing but list of items and Items may be of similar datatypes or
different datatypes under a single name.
Ex:-
$Items=array(1,"Sankar",98.8,true,none);
(or)
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.
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
3. Multidimentional 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 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:
or
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'=>[
'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);
?>
<?php
$fruits=['apple','orange','pear'];
echo sizeof($fruits);
?>
3.in_array() function:
<?php
$fruits=['apple','orange','pear'];
var_dump(in_array('apple',$fruits)); // true
?>
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);
?>
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);
?>
<?php
$fruits=['apple','orange','pear'];
unset($fruits[2]);
print_r($fruits);
?>
<?php
$fruits=['apple','orange','pear'];
$chuncked_array=array_chunk($fruits,2);
print_r($chuncked_array);
7. array_merge() function:
<?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:
<?php
$c=['green'=>'avacado','red'=>'apple','yellow'=>'banana'];
$keys=array_keys($c);
print_r($keys);
?>
<?php
$c=['green'=>'avacado','red'=>'apple','yellow'=>'banana'];
$flipped=array_flip($c);
print_r($flipped);
?>
<?php
$numbers=range(1,20);
print_r($numbers);
?>
Working with Objects:
PHP supports Object oriented Programming.
Object:
Class:
Data abstraction: Providing only essential information about the data and hiding the
background details or implementation.
Class creation:
class classname
public $property1;
private $property2;
protected $property3;
}
Object creation:
$object=new classsname();
Ex:-
<?php
class Myclass
echo $this->greeting;
$obj=new Myclass();
$obj->hello();
?>
output:
- 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 "<br>";
?>
1)printf()
2)sprintf()
1) printf() function:
- printf() function takes two arguments. One is format control string and other is data to be
displayed.
%d To display Integers
%s To display Strings.
Ex:-
<?php
$number=543;
printf("Character %c<br>",$number);
printf("String is %s<br>",$number);
?>
- we can also display data by padding (Leading characters with either 0's or whitespaces or
any character).
Ex:-
<?
printf("%04d<br>",36);
printf("%015d<br>",36);
printf("%'x4d",36);
?>
- 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:
- precision specifier should directly follow the % sign and followed by conversion character.
Ex:-
<?php
printf("%.2f",5.33333333);
?>
2) sprintf() function
- But sprintf() function is used to store the output into a variable for later use.
Ex:-
<?php
$price=sprintf("%.2f",21.3344);
echo $price;
?>
- 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.
1) strlen()
2)strstr()
3)strpos()
4)substr()
5)strtok()
1)strlen() function
syntax:
strlen($string)
Ex:-
<?php
$name1="srikanth";
echo(strlen($name1));
?>
2)strstr() function:
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:
syntax:
strpos($originalstring,"string");
Ex:-
<?php
$string="srikanth";
$position=strpos($string,"ka");
echo $position;
?>
4) substr() function:
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 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)
$token=strtok(" ");
}
?>
<?php
$delimiters = ",";
$token = strtok($delimiters);
?>
- String is nothing but a group of characters which are enclosed by either single quotes or
double quotes.
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
echo trim($name);
?>
ltrim() function:
syntax:
ltrim($string)
Ex:
<?php
echo ltrim($name);
?>
rtrim() function:
syntax:
rtrim($string);
Ex:-
<?php
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
echo strip_tags($name);
?>
substr_replace() function:
syntax:
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
syntax:
wordwrap($string)
Ex:-
<?php
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sit amet accumsan
arcu.";
echo $wrapped;
?>
nl2br() function
syntax:
nl2br($string);
Ex:-
<?php
echo nl2br($string);
?>
explode() function
syntax:
explode(delimiter string,$sourcestring);
Ex:-
<?php
$startdate="2024-07-21";
$datearray=explode("-",$startdate);
foreach($datearray as $e)
echo $e . "<br>";
?>
- These functions allow you to get the current date and time, format dates and times, and
perform various calculations with date and time values.
-- Basic Functions:
date(), time()
-- Formatting Functions:
date()
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:
a: am/pm in lowercase
A: AM/PM in Uppercase
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
$currenttime=time();
?>
mktime() function:
<?php
echo mktime(15, 30, 0, 7, 20, 2024); // Outputs: Unix timestamp for July 20, 2024 15:30:00
?>
strtotime() function:
- The strtotime() function parses an English textual datetime description into a Unix
timestamp.
<?php
?>