Chap2 Functions Arrays and Strings in PHP
Chap2 Functions Arrays and Strings in PHP
Functions:
3. PHPINFO() :
i) It outputs a large amount of information about the current state of PHP.
ii) This includes information about
-PHP compilation options and extensions
-the PHP version
-server information and environment, the PHP environment
- OS version information, paths, master and local values of configuration options
-HTTP headers, and the PHP License.
Funame(arg); //funcall
Arrays:
Advantage:
Types of Arrays:
1. Indexed Arrays
2. Associative Arrays
3. Multidimensional Arrays
1. Indexed Array:
a) Also called Numeric Array.
b) Numeric arrays use integer / numbers as their index number to identify each item
of the array.
c) Array index begin with 0.
d) Indexed array can store numbers, strings, objects or mixed items.
e) PHP index array is created using array()
f) There are 2 ways to define indexed array
i) $arr=array (22,33,44)
ii) $arr[0]=11;$arr[1]=22,$arr[2]=44;
Foreach(Arrvar as $value)
{ echo $value}
<?php
$arr=array(11,22,33);
echo "<br><br>";
var_dump($arr);
$strarr=array("Heena","Reena","Teena");
print_r($strarr);
echo "<br><br>";
var_dump($strarr);
$farr=array(11.4,6.7,8.9);
print_r($farr);
echo "<br><br>";
var_dump($farr);
$marr=array(100,"Heena",99.8);
print_r($marr);
echo "<br><br>";
var_dump($marr);
?>
Demo.PHP
<?php
$arr1=array(22,33,44,55);
$size=count($arr1);
echo "<br> Size of Array=",$size;
for($i=0;$i<$size;$i++)
{
echo "<br>",$arr1[$i];
}
echo "<br> Array using Foreach<br>";
foreach($arr1 as $var)
{
echo $var."<br>";
}
Echo “<br> Array using print_r “;
Print_r($arr);
?>
2. Associative Arrays:
a) Associative array differ from numeric array in the sense that associative arrays
use string as id to access each element of array.
b) It stores data in form of key value pair.
c) Key names can be placed in single quotes or double quotes.
d) If initial index is non-numeric string, still the subsequent indexes will be numbers
beginning at 0.
e) Syntax:
$arr=array(‘keyname’=>value);
$arr[‘keyname’]=value;
Explanation:
Why Associative Array?
To establish strong association between key and value means what if I created
array to store marks of student and from that I want to identify how many
marks are scored by Rahul Can I get to know by using numeric array. Ans is
no so we are going to use associative array
1. <?php
2. $salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
3. foreach($salary as $k => $v) {
4. echo "Key: ".$k." Value: ".$v."<br/>";
5. }
6. ?>
7. //Associative array Demo
8. <?php
9. $arr=array("Heena"=>33,"Teena"=>34,"Reena"=>32);
10. echo "<br> Array:";
11. print_r($arr);
12. echo "<br><br>";
13. var_dump($arr);
14.
15. $arr1=array(33=>"A",34=>"B",35=>"R");
16. echo "<br> Array:";
17. print_r($arr1);
18. echo "<br><br>";
19. var_dump($arr1);
20.
21.
22.
23. ?>
Multidimensional Array:
A multidimensional array is an array which stores another array at each index rather than
storing a single value. In simple words, a multidimensional array is an array of arrays.
As the name suggests, every element in this array can be an array and they can also hold other
sub-arrays within.
Advantage:
<?php
$arr=array(array(101,202,303),array("HTML","CSS","PHP"),
array("HTML"=>2000,"CSS"=>3000,"PHP"=>4000));
print_r($arr);
?>
1. Sorting Functions:
I. On Numeric Array:
a) sort -Sorts numeric array in asc order of their values
b) rsort -Sorts numeric array in descending order of their values.
II. Associative array:
a) Arsort()- Sorts associative array in desc order of their values
b) Krsort()- Sorts associative array in desc order of their keys
a. Array_push() –
2. Is_array()-To check whether the provided data is in form of an array, we can use
the is_array() function. It returns True if the variable is an array and
returns False otherwise.
Syntax: is_array($arr)
3. In_array() -When using an array, we may often want to check whether a certain value is
present in the array or not.
Syntax: in_array($var,$arr)
5. Sizeof($arr)- Returns size of Array i.e number of elements present in array. On success it
returns true. It is same like count()
6. Array_merge($arr1,$arr2): It combines two different arrays into a single array, you can
do so using this function. It doesn't matter whether the arrays to be combined are of same
type(indexed, associative etc) or different types, using this function we can combine them
into one single array.
7. Array_values($arr)- In an array, data is stored in form of key-value pairs, where key
can be numerical(in case of indexed array) or user-defined strings(in case of
associative array) and values. If we want to take all the values from our array, without
the keys, and store them in a separate array, then we can use array_values() function.
8. array_keys($arr):Just like values, we can also extract just the keys from an array.
Demo.php
<?php
$arr1=array(11,22,33,55);
$arr2=array("Neha"=>"HTML","Amit"=>"CSS","Ram"=>"PHP");
$var=100;
$val=22;
echo"<br><h1>Size of Array1 is",sizeof($arr1);
echo"<br><h1>Size of Array2 is",sizeof($arr2);
echo is_array($var)?"<br>Is Array":"<br>Is not Array";
echo in_array($val,$arr1)? "<br> Is present":"<br> Not Present";
$arr3=array_merge($arr1,$arr2);
echo "<br> Array 3 is <br>";
print_r($arr3);
echo "<br> Array 3 Values are <br>";
print_r(array_values($arr3));
echo "<br> Array 3 keys are <br>";
print_r(array_keys($arr3));
echo "<br> Array after insertion<br>";
array_push($arr3,100,200);
print_r($arr3);
echo "<br> Array after Deletion<br>";
array_pop($arr3);
print_r($arr3);
?>
<?php
$arr=array(11,22,33,44);
echo "<br> Array is<br>";
print_r($arr);
$val=array_pop($arr);
echo "Value=",$val;
echo "<br> After deletion of last ele from Array is<br>";
print_r($arr);
?>
9. Array_shift($arr):
It removes the first element from an array, and returns the value of the removed
element.
Note: If the keys are numeric, all elements will get new keys, starting from 0 and
increases by 1
Difference between in_array and array_search is that in_Arry() returns true or false
whereas array_search returns key of corresponding value else false
10. Array_reverse($arr): Reverses entire array and returns reversed array.
12. array_slice($arr, $startpos, $length) :This function is used to create a subset of any
array. Using this function, we define the starting point($offset, which is the array index
from where the subset starts) and the length(or, the number of elements required in the
subset, starting from the offset).
If length is omitted then array_slice returns all elements from start pos.
Syntax: array_slice ($arr,start pos of new arr, no of eles in new arr);
Demo.php
<?php
//$arr=array("h"=>"html","p"=>"php","c"=>"css","j"=>"java");
//$arr=array(1=>"one",2=>"two",3=>"three");
$arr=array(11,22,33,44,55,66,77);
echo "<br>Array is <br>";
print_r($arr);
//echo "<br>Reverse Array <br>";
//arsort($arr); //desc order
//print_r(array_reverse($arr));
//echo "<br> Flipped Array<br>";
//print_r(array_flip($arr));
echo "<br>Subset of Array<br>";
print_r(array_slice($arr,2,4));
?>
13. array_rand($arr): Returns a random key from an array, or it returns an array of random
keys. When picking only one entry, array_rand() returns the key for a random entry.
Otherwise, an array of keys for the random entries is returned. This is done so that
random keys can be picked from the array as well as random values. Trying to pick more
elements than there are in the array will result in an E_WARNING level error, and NULL
will be returned.
Syntax : array_rand($arr,number)
<?php
$arr=array(11,22,33,44);
print_r($arr);
$key=array_rand($arr);
or
$keys=array_rand($arr,2);
Echo $arr[$[keys[0]],”<br>”,$arr[$keys[0]];
?>
Note: When every time u do refresh new val is stored in $key1
14. array_map(‘”fun name”,$arr):It modifies all elements one or more arrays according to
some user-defined condition in an easy manner. It basically, sends each of the elements
of an array to a user-defined function and returns an array with new values as modified
by that function.
Syntax: array array_map(“funname”,$arr);
15. array_pad() –It inserts a specified number of elements, with a specified value, to an
array. array_pad() returns a copy of the array padded to size specified by size with
value value. If size is positive then the array is padded on the right, if it's negative then on
the left.
Ex: $a=array(10,20);
Print_r($b);
<?php
$arr=array(11,22,33,44,55);
?>
18.array_diff (): It is used to calculate the difference between two or more arrays.
This function computes difference according to the values of the elements, between one or more
array and return differences in the form of a new array. This function basically returns all the
entries that are present in the first array which are not present in any other arrays. If all entries of
different arrays is same then it returns empty array
Syntax: array array_diff($arr1,$arr2….);
<?php
$arr1=array(11,22,33,44);
$arr2=array( 11,22,33);
$res=array_diff($arr1,$arr2);
echo "<br>Result=";
print_r($res);
//$b=array_chunk($arr,2);
//echo "<br>Array B :";
//print_r($b);
//$sum=array_sum($arr);
//echo "<br> Sum of Eles=",$sum;
?>
18. list() –
i) It is used to assign array values to multiple variables at a time. This function will
only work on numerical arrays.
ii) When the array is assigned to multiple values, then the first element in the array is
assigned to the first variable, second to the second variable and so on, till the
number of variables.
iii) The number of variables cannot exceed the length of the numerical array.
Number of variables must not be less also.
Syntax: list($v1,$v2…);
<?php
$arr1=array(11,22,33);
//list($a,$b,$c)=$arr1;
//echo "<br>A=",$a;
//echo "<br>B=",$b;
//$arr2=array("H"=>"HTML","P"=>"PHP");
?>
19. Shuffle():
i) It is used to shuffle or randomize the order of the elements in an array.
ii) This function assigns new keys for the elements in the array.
iii) It will also remove any existing keys, rather than just reordering the keys and
assigns numeric keys starting from zero.
iv) On success it returns true else false
Note: shuffle() changes the keys of an array, which you pass by reference. If you print the array
after you shuffle it, the elements will be in a random order. array_rand() does not shuffle the
array (i.e. it does not change the keys), but it returns one or more randomly selected keys from
the array. If you print the array after this, it will still be in its original order.
<?php
$arr1=array(11,22,33);
echo "Array<br>";
print_r($arr1);
shuffle($arr1);
print_r($arr1);
$arr2=array("H"=>"HTML","P"=>"PHP");
echo "Array<br>";
print_r($arr2);
shuffle($arr2);
print_r($arr2);
?>
20. Compact() –
<?php
$a="Amit";
$b="Bala";
$c="Ceena";
$arr1=compact("a","b","c");
echo "<br>New Array<br>";
print_r($arr1);
?>
21. Array_unique($arr) :
22. Array_fill () – It is used to fill an array with values. This function basically creates an
user-defined array with a given pre-filled value.
Syntax:
array_fill($start_index, $number_elements, $values)
Parameter:
The array_fill() function takes three parameters and are described below:
Where,
i) $start_index: It is starting position of filling up the values into the array, the
user wants to create. This is a mandatory parameter and must be supplied.
ii) $number_elements: This parameter refers to the number of elements, the user
wants to enter into the array. The $number_elements should be positive
otherwise E_WARNING is thrown. This is also a mandatory parameter.
iii) $values: This parameter refers to the values we want to insert into the array.
These values can be of any type.
iv) Return Type: The array_fill() function returns a filled user-defined array,
with values described by $value parameter.
<?php
$arr1=array_fill(1,3,"A");
echo "<br>Array<br>";
print_r($arr1);
?>
23. Range() : It fills an array with a series of values. You can specify numbers or
characters as the start and end values for your series.
<?php
$arr1=array_fill(1,3,"A");
echo "<br>Array<br>";
print_r($arr1);
$arr1=range('a','e');
print_r($arr1);
?>
Syntax: array_intersect($arr1,$arr2)
<?php
$arr1=array(11,22,33,44,55);
$arr2=array(55,22,33);
$arr3=array_intersect($arr1,$arr2);
echo "<br>Array3<br>";
print_r($arr3);
?>
25. Array_combine() :
i) The array_combine() is an inbuilt function in PHP which is used to combine two
arrays and create a new array by using one array for keys and another array for
values.
ii) Both arrays must have equal number of elements
<?php
$aunion= array_merge(
array_intersect($x, $y),
array_diff($x, $y),
array_diff($y, $x)
);
return $aunion;
$a = array(1, 2, 3, 4);
$b = array(2, 3, 4, 5, 6);
print_r(array_union($a, $b));
?>
Extract : Now I have associative array with keys and values. We will convert keys to variables
$color=array(‘a’=>’red’,’ b’ =>’blue’); I want to convert keys a to $a and so on
Syntax: extract(arr,extract_rules,prefix) It converts keys to variables
Strings:
1. String is sequence of characters.
2. String is one of the data types supported by PHP.
3. The string variables can contain alphanumeric characters. Strings are created when;
4. You declare variable and assign string characters to it
5. You can directly use them with echo statement.
Single Quotes –
i) The string within single quote is displayed as it is.
ii) When string is specified in single quotes PHP will not evaluate value of variable
Double Quotes:
i) When strings are specified in double quotes ,PHP will evaluate value of variable.
2. Ucwords() -It converts the first character of each word to uppercase in a string.
Syntax: ucwords($str)
3. Lcfirst()- Converts first character of string in lowercase and remaining all chars remained
unchanged.
Syntax: lcfirst($str)
2. Str_word_count() -It is used to return information about words used in a string like total
number word in the string, positions of the words in the string etc.
2. substr_count():
Syntax: substr_count($str,$substr,$start,$len);
1. Str_pad_both:
2. Str_pad_left:
3. Str_pad_right:
Syntax: str_replace(find,replace,string)
4. Strpos: It finds the position of the first occurrence of a string in another string.
This returns an integer value of the position of the first occurrence of the
string. This function is case-sen sitive, which means that it treats upper-case
and lower-case characters differently.
Syntax: str_pos(String,search,start_pos)
Syntax: str_shuffle($str)
Syntax: str_split(Str,length)
Syntax: htmlentities($str)
Example:
<?php
$str=”<a href=”www.dypiu.ac.in>DYPIU</a>”;
Echo htmlentities($str);
?>
VI. Comparision of Strings: PHP provides 4functions and 2 operators for comparing
two strings
1. Strcmp () – It is casesensitive function that compares 2 strings.
It returns following values
0=> Indicates both strings are equal
+ve=>Indicates s1>s2
-ve=> Indicates s1<s2
3. Strncmp() -It case-sensitive function which is used to compare first n character of two
strings
Syntax: strncmp(s1,s2,val);
Syntax: strncmp(s1,s2,val);
1. == operator : Returns true if both strings are equal .i.e. values in string are equal
2. === operator: Returns true if both strings are iden
3. tical .i.e. values as well as type both are same.
4. Relational operators also works on string
<?php
/* $s1="Akurdi";
echo "<br>String is : $s1";
$s2=str_pad($s1,12,'*'); //by default right
$s3=str_pad($s1,12,'$',STR_PAD_LEFT);
echo "<br>Padded String:",$s2;
echo "<br>Padded String:",$s3;
echo "<br>Padded String:",$s3;
echo "<br>Padded String:",str_pad($s1,15,'@',STR_PAD_BOTH);*/
?>