Php - (Unit- 2) Notes
Php - (Unit- 2) Notes
Page 1
Page 2
Index
1. String in PHP
2. String Functions
3. Array in PHP
Page 3
1. String
A string is a series of characters. There are exactly 256 different characters
possible. The present stable versions of PHP – PHP4 and PHP5, have no native
support for Unicode. There aren’t string length limitations in PHP except the
server’s available memory and the configuration of the php.ini settings file.
The string, like a variable, will have to be created first. There are two ways to use a
string in PHP – you can store it in a function or in a variable. In the example below,
we will create a string twice – the first time storing it in a variable, and the second
time – in a function, in our case – an echo
Basic Example
<?php
?>
String basics
Page 5
Output
Hello $a
Hello PHPGURUKUL
welcome
Clearly, this “simple” syntax won’t work in those situations in which the name of
the variable you want to interpolated is positioned in such a way inside the string
that the parser wouldn’t be able to parse its name in the
way you intend it to. In these cases, you can encapsulate the variable’s name in
braces.
$me = ’Davey’;
{$names[1]}[1987]";
"World"; echo
<<<TEXT
So I said, "Hello
$who" TEXT;
Page 7
echo ’This is ’my’ string’;
$a = 10;
String as arrays
You can access the individual characters of a string as if they were members of an
array.
$string = ’abcdef’;
$string = ’123aa’;
if ($string == 123) {
Page 8
// The string equals 123
• You’d expect this comparison to return false, since the two operands are not
the same. However, PHP first transparently converts the contents of $string to
the integer 123, thus making the comparison true.
• Naturally, the best way to avoid this problem is to use the identity operator
===
Page 9
2. String functions
strcmp(), strcasecmp() both returns zero if the two strings passed to the function
are equal. These are identical, with the exception that the former is case-sensitive,
while the latter is not.
strcasencmp() allows you to only test a given number of characters inside two
strings.
$s1 = ’abcd1234’;
$s2 = ’abcd5678’;
// Compare the first four characters
echo strcasencmp ($s1, $s2, 4);
Page
10
String functions –strlen()
Output – 28
Page 11
String functions –strtr()
• Output – 1bc
Multiple-character version
<?php
$subst = array (’1’ => ’one’,’2’ => ’two’);
echo strtr (’123’, $subst);
?>
Output- onetwo3
• strpos() allows you to find the position of a substring inside a string. It returns
either the numeric position of the substring’s first occurrence within the string,
or false if a match could not be found.
• You can also specify an optional third parameter to strpos() to indicate that you
want the search to start from a specific position within the haystack.
<?php
$haystack = ’123456123456’;
$needle = ’123’;
echo strpos ($haystack, $needle);
Page
12
echo strpos ($haystack, $needle, 1);
?>
Output –
0
6
Page
13
echo stripos(’Hello World’, ’hello’);
Output- 0
Strpos() does the same as strpos(), but in the revers order.
echo strrpos (’123123’, ’123’);
Output- 3
The strstr() function works similarly to strpos() in that it searches the main string
for a substring. The only real difference is that this function returns the portion of
the main string that starts with the sub string instead of the latter’s position:
$haystack = ’123456’;
$needle = ’34’;
Output- 3456
Output- My World
https://phpgurukul.com/php-tutorials/ Page 8
Output- Hello Reader
Optionally, you can specify a third parameter, that the function fills, upon return,
with the number of substitutions made:
$a = 0;
echo $a;
Output- 3
If you need to search and replace more than one needle at a time, you can pass the
first two arguments to str_replace() in the form of arrays.
"HelloWorld");
Page 9
echo str_replace(array("Hello", "World"), "Bye", "Hello World");
The very flexible and powerful substr() function allows you to extract a substring
from a larger string.
Page 10
echo substr ($x, 0, 3);//
-2); //outputs 67
Page 11
Page 12
3. Array
An array is a group of the same data type which is used to store multiple values in
a single variable. In an array each data item is referenced by its name and a number
that is called a subscript. The elements of an array are accessed by specifying a
subscript after the array variable name. The first element of an array has a subscript
of 0, the next is 1, and so on. The last element has a subscript of n-1, where n is the
number of elements.
Types of Array
Page 13
Page 14
Numeric Index Array
A numeric index array stores each array element with a numeric index i.e.
subscript. In a numeric indexed array, the keys are numeric and starts with
subscript of 0, the next is 1, and so on. Numeric indexed arrays use
integer/numbers as their index number to identify each item of the array.
There are two ways to define the numeric index array in PHP.
Page 15
Page 16
Example 1
<?php
echo
$empname[1].'<br>';
echo $empname[2];
?>
Output
Page 17
Page 18
Associative Array
An Associative array also is a type of array by which you can assign an arbitrary
key to every value. In an associative array, each key is associated with a value.
With associative arrays we can use the values as keys and assign values to them. In
an associative array, the keys are not necessarily numeric, and even when they are
numeric, not necessarily in any order.
Example 1
<?php
$studentpercent ['Anuj'] = "76";
$studentpercent ['Sanjeev'] = "68";
$studentpercent ['Rahul'] = "90";
echo "This is First Example of Associative Array" .'<br>'.'<br>';
echo "Anuj have " . $studentpercent ['Anuj'] . " Percent marks in B.Tech.";
?>
Page 19
Output
Page 20
Multidimensional Array
Example1
<?php
$myLists['Employee'] = array("1"=>"Anuj Kumar",
"2"=>"Sanjeev kumar",
"3"=>"Rahul Chaubey",
"4"=>"Atul Raguvanshi",
"5"=>"Ashish Jain");
echo "This is the First Example of Multidimensional Array".'<br>'.'<br>';
echo $myLists ['Employee'][5] . " is a owner of company .";
?>
Output
Page 21
Page 22
4. Useful functions for arrays in PHP
sizeof($arr)
<?php
?>
Output
Array has 3 elements
array_values($arr)
Page 23
This function accepts a PHP array and returns a new array containing
only its values (not its keys). Its counterpart is the array_keys() function.
Use this function to retrieve all the values from an associative array.
Ex –
<?php
$data = array("hero" => "Holmes", "villain" => "Moriarty");
print_r(array_values($data));
?>
Output
Page 24
Array
(
[0] => Holmes
[1] => Moriarty
)
array_keys($arr)
This function accepts a PHP array and returns a new array containing only its keys
(not its values). Its counterpart is the array_values() function.
Use this function to retrieve all the keys from an associative array.
Ex-
<?php
$data = array("hero" => "Holmes", "villain" => "Moriarty");
print_r(array_keys($data));
?>
Output:
Array
(
[0] => hero
[1] => villain
)
Page 25
array_pop($arr)
array_pop($data);
print_r($data);
?>
Page 26
Output
Array
(
[0] => Donald
[1] => Jim
)
array_push($arr, $val)
Ex-
<?php
"Tom"); array_push($data,
"Harry"); print_r($data);
?>
Output
Array
(
Page 27
[0] => Donald
[1] => Jim
[2] => Tom
[3] => Harry
)
array_shift($arr)
Page 28
Ex-
<?php
array_shift($data);
print_r($data);
?>
Output
Array
(
[0] => Jim
[1] => Tom
)
array_unshift($arr, $val)
This function adds an element to the beginning of an array.
<?php
Page 29
"Tom"); array_unshift($data,
"Sarah"); print_r($data);
?>
Output:
Array
([0] => Sarah
[1] => Donald
[2] => Jim
[3] => Tom
)
Page 30
each($arr)
This function is most often used to iteratively traverse an array. Each time each() is
called, it returns the current key-value pair and moves the array cursor forward one
element. This makes it most suitable for use in a loop.
Ex-
<?php
?>
Output:
hero: Holmes
villain: Moriarty
sort($arr)
This function sorts the elements of an array in ascending order. String values will be arranged in
ascending alphabetical order.
Note: Other sorting functions include asort(), arsort(), ksort(), krsort() and rsort().
Page 31
Ex-
<?php
"s"); sort($data);
print_r($data);
?>
Page 32
Output
Array
(
[0] => a
[1] => g
[2] => s
[3] => t
)
array_flip($arr)
The function exchanges the keys and values of a PHP associative array.
Use this function if you have a tabular (rows and columns) structure in an array,
and you want to interchange the rows and columns.
Ex-
<?php
print_r(array_flip($data));
?>
Output
Page 33
Array
(
[apple] => a [ball]
=> b
)
array_reverse($arr)
The function reverses the order of elements in an array.
Use this function to re-order a sorted list of values in reverse for easier processing—
for example, when you’re trying to begin with the minimum or maximum of a set of
ordered values.
Page 34
Ex-
<?php
60);
print_r(array_reverse($dat
a));
?>
Output
Array
(
[0] => 60
[1] => 25
[2] => 20
[3] => 10
)
array_merge($arr)
This function merges two or more arrays to create a single composite array. Key
collisions are resolved in favor of the latest entry.
Page 35
Use this function when you need to combine data from two or more arrays into a
single structure—for example, records from two different SQL queries.
Ex-
<?php
print_r(array_merge($data1,
$data2));
?>
Page 36
Output
Array
(
[0] => cat
[1] => goat
[2] => dog
[3] => cow
)
array_rand($arr)
This function selects one or more random elements from an array.
Use this function when you need to randomly select from a collection of discrete
values—for example, picking a random color from a list.
Ex-
<?php
?>
Page 37
Output
array_search($search, $arr)
This function searches the values in an array for a match to the search term, and
returns the corresponding key if found. If more than one match exists, the key of
the first matching value is returned.
Use this function to scan a set of index-value pairs for matches, and return the
matching index.
Page 38
Ex-
<?php
?>
Output
Found blue
Use this function to break a larger array into smaller ones—for example, when
segmenting an array by size (“chunking”) or type of data.
Ex-
Page 39
<?php
?>
Page 40
Output
Array
(
[0] => strawberry
[1] => mango
)
array_unique($data)
This function strips an array of duplicate values.
Use this function when you need to remove non-unique elements from an array—
for example, when creating an array to hold values for a table’s primary key.
Ex-
<?php
$data =
array(1,1,4,6,7,4);
print_r(array_unique($data)
);
?>
Page 41
Output
Array
(
[0] => 1
[3] => 6
[4] => 7
[5] => 4
)
Page 42
array_walk($arr, $func)
Use this function if you need to perform custom processing on every element of an
array—for example, reducing a number series by 10%.
Ex-
<?php
$data =
array(10,20,30,40);
array_walk($data,
'reduceBy10');
print_r($data);
Page 43
?>
Output
Array
([0] => 9
[1] => 18
[2] => 27
[3] => 36
)
Page 44
5. Sorting Arrays in PHP
• sort()
• asort()
• rsort()
• arsort()
Page 45
Page 46
sort() function
Using the sort() function you can sort easily and simply. The example of the sort()
function is as follows
<html>
<body bgcolor="pink">
<h3>Sort() Function</h3>
<?php
$name=array
("Anuj","Sanjeev","Manish","Rahul"); echo
print_r($name).'<br>'.'<br>';
sort($nam
e);
echo"<br/>
";
echo"<br/>
";
Page 47
echo "<b>After sorting values
become:</b>".'<br>'; print_r($name).'<br>';
?>
</body>
</html>
In the above example we defined four elements (names) in the array. In this example we
used the sort() function. The sort() function arranges the elements of an array in
ascending (alphabetically) order. You can see in the following image
Page 48
Page 49
Page 50
asort() function
In the example above you saw that the elements of the array are arranged in
ascending (alphabetically) order. The asort() function sorts an array and also
maintains the index position. An example of the asort() function is as follows:
Ex-
<html>
<body bgcolor="pink">
<h3>Sort() Function</h3>
<?php
$name=array
("Anuj","Sanjeev","Manish","Rahul"); echo
print_r($name).'<br>'.'<br>';
asort($name);
echo"<br/>";
echo"<br/>";
become:</b>".'<br>'; print_r($name).'<br>';
?>
Page 51
</body>
</html>
Output — In this output you will see the array sorted by their index position.
Page 52
Page 53
Page 54
rsort() function
Ex-
<html>
<body bgcolor="pink">
<h3>Sort() Function</h3>
<?php
$name=array
("Anuj","Sanjeev","Manish","Rahul"); echo
print_r($name).'<br>'.'<br>';
rsort($name);
echo"<br/>";
echo"<br/>";
become:</b>".'<br>'; print_r($name).'<br>';
?>
Page 55
</body>
</html>
Output— In this output you will see the array sorted in a descending
(alphabetically) order.
Page 56
Page 57
Page 58
arsort() function
The arsort() function is a combination of asort() + rsort(). The arsort() function will
sort an array in reverse order and maintain index position. The example of the
arsort() function is as follows:
Ex-
<html>
<body bgcolor="pink">
<h3>Sort() Function</h3>
<?php
$name=array
("Anuj","Sanjeev","Manish","Rahul"); echo
print_r($name).'<br>'.'<br>';
arsort($name)
; echo"<br/>";
echo"<br/>";
become:</b>".'<br>'; print_r($name).'<br>';
Page 59
?>
</body>
</html>
Page 60
Page 61
Page 62