Unit - Ii Array & String
Unit - Ii Array & String
PHP indexed array can store numbers, strings or any object. PHP indexed array is also
known as numeric array.
P.No:4
PHP Looping with associative array using for each Loop
The for each loop-Loops through a block of code for each element in an array.
PHP foreach loop is utilized for looping through the values of an array. It loops over
thearray,andeachvalueforthefresharrayelementisassignedtovalue,andthearray pointer is
progressed by one to go the following element in the array.
The foreach loop works only on arrays, and is used to loop through eachkey / value pairin
an array.
Syntax:
foreach($arrayas$key=>$value){
codetobeexecuted;
}
Foreveryloopiteration,thevalueofthecurrentarrayelementisassignedto$key=>
$valueandthearraypointerismovedbyone,untilitreachesthelastarrayelement.
Thefollowingexamplewilloutputboththekeysandthevaluesofthegivenarray($age):
Example:
<?php Output:
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
Peter=35
foreach($age as $x => $val) { Ben=37
echo "$x = $val<br>"; Joe=43
}
?>
The foreach loop is concerned with the master array element, $age. It loops through this
array and assigns the temporary name $x for key and $val for the value of age to theelement
contained within each position.
P.No:5
PHP–String
Syntax
The syntax of the str_replace() function is given below, which has the following four
parameters.
Parameter
The str_replace() function has four parameters in which three are mandatory, and the
remaining one is an optional parameter.All these following parameters are described below:
$search(mandatory)- This parameter is a mandatory parameter that can have both string
and array type values. The $searchp arameter contains the value which is going to be
searched for the replacement in the given $source.
$count (mandatory) - It is the last and optional parameter. It is an integer variable which
counts the number of replacements done in the string. Simply, this variable stores the total
number of replacement performed on a given string $source.
P.No:6
Example1: Basic example with string variable (replaceoneword)
<?php
$source="Hiieveryone!";
$search='Hii';
$replace='Hello';
echo '<b>'."String before replacement:".'</br></b>';
echo $string.'</br>';
$newstr = str_replace($search, $replace, $source, $count);
echo '<b>'."New replaced string is:".'</br></b>';
echo$newstr.'</br>';
echo'Numberofreplacement='.$count;
?>
Output:
String before replacement: Hii everyone!
New replaced string is: Hello everyone!
Number of replacement = 1
<?php
$source = "Hii everyone! welcome to java website. We will get best technical
content here.";
$search=array("Hii","We");
$replace=array("Hello","You");
echo '<b>'."String before replacement:".'</br></b>';
echo $string.'</br>';
$newstr = str_replace($search, $replace, $source, $count);
echo '<b>'."New replaced string is:".'</br></b>';
echo$newstr.'</br>';
echo'Numberofreplacement='.$count;
?>
Output:
String before replacement:
Hii everyone! Welcome to javawebsite.Wewillgetbesttechnicalcontenthere.
Newreplacedstringis:
Hello everyone! welcome to java website. You will get best technical content here.
Number of replacement = 2
P.No:7
Formatting String
PHP string printf() function predefined functions. It is used to output a formatted string.
Wecanpass the arg1, arg2, arg++ parameters at percent(%) signs in themain string.
Syntax:
printf(format,arg1,arg2,arg++);
P.No:8
Example(a)
<?php
$version=4;
$str="Inthisbook";
printf("WeareLearningPHP%uform%s.",$version,$str);
?>
Output:
WeareLearningPHP4formInthisbook.
Example(b)
<?php
$number = 54345;
printf("%f",$number);
$number=6;
printf("Binarynumber:%b",$number);
$number=12;
printf("OctalNumber:%o",$number);
?>
Output:
54345.000000
Binarynumber:110
OctalNumber:14
Example(c)
<?php Output:
?>
P.No:9
b) PHP strings printf() Function
The sprintf( ) is an in-built function of PHP which writes a formatted string to a variable. It
returns a formatted string. PHP 4 and above versions support sprintf() function.
Thesprintf()functionissimilartotheprintf()function,buttheonlydifferencebetween
bothofthemisthatsprint()savestheoutputintoastringinsteadofdisplayingthe formatted message
on browser like printf( ) function.
The sprintf( ) works with echo. The formatted string returns by the sprintf( ) function is
printed byecho on the browser whereas printf( ) directly put the output onbrowser.
<html>
<body>
<?php
$number=123;
$txt=sprintf("With2decimals:%1\$.2f
<br>With no decimals: %1\$u",$number);
echo $txt;
?>
</body>
</html>
Output:
P.No:10
String Related Library function and regular expression
Ingeneralpractice,usingthestringfunctionwillsavealotoftimeastheyarepre-defined in PHP
libraries. We to do is call them and use them which are in-built functions for string processing
in PHP.
BelowwehavealistofsomecommonlyusedstringfunctionsinPHP:
a) strlen($str)
This function returns the length of the string or the number of characters in the string
including whitespaces.
<?php
$str="WelcometoAll";
echo"Lengthofthestringis:".strlen($str);
?>
Output:
Lengthofthestringis:13
b) str_word_count($str)
This function returns the number of words in the string. This function comes in handly in
form field validation for some simple validations.
<?php
$str="Welcometoall";
//usingstr_word_countinechomethod
echo"Numberofwordsinthestringare:".str_word_count($str);
?>
Output:
Numberofwordsinthestringare:3
c) strrev($str)
Output:
Reverse:llAotemocleW
P.No:11
d) strpos($str,$text)
<?php
$str="WelcometoAll";
//usingstrposinechomethod
echo"Positionof'All'instring:".strpos($str,'All');
?>
Output:
Positionof'All'instring:11
e) ucwords($str),ucfirst($str),lcfirst($str)
Thesefunctionisusedforformattingthestring.
<?php
$str = "welcome to all"
echo ucwords($str);
?>
Outupt:
WelcomeToAll
f) strtoupper($str)
To convert every letter/character of every word of the string to uppercase, one can
use strtoupper() method.
<?php
$str = "welcome to
all";echo strtoupper($str);
?>
Output:
WELCOMETO ALL
P.No:12
g) strtolower($str)
To convert every letter/character of every word of the string to uppercase, one can
use strtolower() method.
<?php
$str="WELCOMETO ALL";
echostrtolower($str);
?>
Output:
Welcometoall
h) str_repeat($str,$counter)
This function is used to repeat a string a given number of times. The first argument is the
string andthe second argument is thenumberoftimes thestringshould berepeated.
<?php
$str = "Welcome to all";
echostr_repeat($str,4);
?>
Output:
WelcometoallWelcometoallWelcometoallWelcometoall
i) strcmp($str1,$str2)
function is used to compare two strings. The comparison is done alphabetically. If the first
string is equal to the second string, the result will be equal to 0. If the first string is greater
than second string, the result will be greater than 0, and if the second string is greater than
the first string, then the result will be less than 0.
<?php
$str1="Study";
$str2="Studywell";
// comparing str1 with str1
echostrcmp($str1,$str1);
// comparing str1 and str2
echostrcmp($str1,$str2);
// comparing str2 and str1
echostrcmp($str2,$str1);
?>
P.No:13
j) substr($str,$start,$length)
This function is used to take out a part of the string(substring), starting from a particular
position, of a particular length.
The first argument is the string itself, second argument is the starting index of thesubstring
to be extracted and the third argument is the length of the substring to be extracted.
<?php
$str="WelcometoAll";
echosubstr($str,3,7); //(from3to9–7letter)
?>
Output:
cometo
k) trim($str,charlist)
This function is used to remove extra whitespaces from beginning and the end of a string.
Thesecondargument charlist isoptional.Wecanprovidealist ofcharacter,justlike a string,as the
second argument, to trim/remove thosecharacters fromthe main string.
<?php
$str1 ="Hello World";
echotrim($str1)."<br/>";
$str2 = "Hello Hello";
echo trim($str2,"Heo");
?>
Output:Hell
oWorldllo
Hell
P.No:14
P.No:15