0% found this document useful (0 votes)
40 views15 pages

Unit - Ii Array & String

Php notes for array and strings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views15 pages

Unit - Ii Array & String

Php notes for array and strings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

UNIT - II

Array & String

Creating Index based Array


P.No:2
P.No:3
PHP Looping with Indexed based Array

PHP indexed array is an array which is represented by an index number by default.All


elements of array are represented by anindex number which starts from 0.

PHP indexed array can store numbers, strings or any object. PHP indexed array is also
known as numeric array.

PHP Indexed Array Example


<?php Output:
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
Volvo

for($x = 0; $x < $arrlength; $x++) { BMW


echo $cars[$x]; Toyota
echo"<br>";
}
?>

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

String Searching & Replacing String

The str_replace ( ) function is a case-sensitive, built-in function of PHP which replaces


some character of the string with other characters. It is used to replace all the occurrences of
the search string with the replacement string.

Syntax

The syntax of the str_replace() function is given below, which has the following four
parameters.

$newstr = str_replace ( $search, $replace, $source, $count)

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.

$replace (mandatory) - This parameter is a mandatory parameter which is replaced with


the search values.In simple words-this parameter holds that value which will replace the
$search value in the given $ source.

$source(mandatory)- This parameter is also a mandatory parameter which is an array or


string in which search and replace value is searched and replaced. It is the string or array
with which we are working.

$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

Example2:Replacement with array variable (replacemorethanoneword)


To replace the multiple values in the $string, we have to take an array to store these values for
replacement.

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

a) PHP string printf() Function

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++);

Parameter Description Required/Optional

format Specifythestring.Followingarethe possible Required


format values:
 %%-Returnsapercentsign
 %b:Binarynumber
 %c:Thecharacteraccordingtothe ASCII
value
 %d : Signed decimal number
(negative, zero or positive)
 %e : Scientific notation using a
lowercase (e.g. 1.2e+2)
 %u : Unsigned decimal number (equal
to or greather than zero)
 %f : Floating-point number (local
settings aware)
 %g:shorterof%eand%f
 %G:shorterof%Eand%f
 %o:Octalnumber
 %s:String
 %x : Hexadecimal number (lowercase
letters)

arg1 The argument to be inserted at the first %- Required


sign.

arg2 Theargument to be inserted at the Optional


second%-sign.

arg++ Theargumenttobeinsertedatthe third,fourth, optional


etc. %s sign

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:

echo “<pre>”; Books


printf(“%20s\n”, “Books”); CDs
printf(“%20s\n”,“CDs”);
DVDs
printf(“%20s\n”,“DVDs”);
printf(“%20s\n”, “Games”); Games
printf(“%20s\n”, “Magazines”); Magazines
echo “</pre>”;

?>

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:

With 2 decimals: 123.00


With no decimals: 123

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)

This function is used to reverse a string.

Let's take an example and see,


<?php
$str="WelcometoAll";
// using strrev in echo method
echo"Reverse:".strrev($str);
?>

Output:
Reverse:llAotemocleW

P.No:11
d) strpos($str,$text)

Thisfunctionisusedtofindthepositionofanytext/wordinagivenstring.Justlike anarray, string


alsoassignindex valuetothe characters storedin it, starting fromzero.

<?php
$str="WelcometoAll";
//usingstrposinechomethod
echo"Positionof'All'instring:".strpos($str,'All');
?>

Output:
Positionof'All'instring:11

e) ucwords($str),ucfirst($str),lcfirst($str)

Thesefunctionisusedforformattingthestring.

ucwords($str) function converts first letter/character of every word in the string to


uppercase.

ucfirst($str) function converts first letter/character of given string to uppercase.

lcfirst($str) function converts first letter/character of given string to lowercase.

Let's take an example and see,

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

You might also like