0% found this document useful (1 vote)
191 views23 pages

Chap2 Functions Arrays and Strings in PHP

1. Functions in PHP allow for easy code maintenance and reusability. There are built-in functions like gettype() and phpinfo() as well as user-defined functions. 2. Arrays allow for storing multiple values in a single variable. There are indexed, associative, and multidimensional arrays. Array functions like sort(), push(), pop(), and merge() allow for manipulating array elements. 3. Strings in PHP can be stored in arrays and manipulated using functions. Common string functions check data type, validate values, and output system information.

Uploaded by

Tanmay Vaij
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (1 vote)
191 views23 pages

Chap2 Functions Arrays and Strings in PHP

1. Functions in PHP allow for easy code maintenance and reusability. There are built-in functions like gettype() and phpinfo() as well as user-defined functions. 2. Arrays allow for storing multiple values in a single variable. There are indexed, associative, and multidimensional arrays. Array functions like sort(), push(), pop(), and merge() allow for manipulating array elements. 3. Strings in PHP can be stored in arrays and manipulated using functions. Common string functions check data type, validate values, and output system information.

Uploaded by

Tanmay Vaij
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 23

Chap2: Functions , Arrays and Strings in PHP

Functions:

i) It is set statements that performs well defined task


ii) Purpose of Functions:
a) Easy maintenance of code
b) Reusability of Code
iii) There are two types of Functions
a) Built In functions
b) User defined Functions
a) Built In Functions:

1. Gettype() : It checks type of existing variable.

Syntax: string gettype($var);

Where it accepts a single parameter $var. It is the name of variable which is needed to be


checked for type of variable. It returns string type whose possible values are Boolean, integer,
double, string, array, object, resource, NULL etc.

2. PHP Data Validation Functions:


a) Is_integer($var): Checks whether given parameter is integer or not. On success
returns true.
b) Is_double($var):
c) Is_numeric($var) :Checks whether given parameter is integer or double.
d) Is_string($var)-
e) Is_bool($var)
f) Empty($var): Checks whether data value is 0,0.0, “0”,false,NULL,empty array

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.

b) User Defined Functions:

Syntax: function funname(arg)

Funame(arg); //funcall

Arrays:

1. It is collection of similar kind of data.


2. It holds multiple values in single variable.
3. Each element of array has its own index so it can be easily accessed.
4. An array is created using an array() function in PHP

Note: PHP allows an array to contain elements of different datatypes.

Advantage:

1. No need to define multiple variables.


2. Easy to traverse: By the help of single loop, we can traverse all the elements of array.
Functions to display entire array
3. print_r():
It is used to display an array because you cannot print an array with echo or print function
(both are used to display output) though you can use echo or print to display single items
from the array

4. var_dump()- Displays type of var and its value in specific format.


Its value is in the following format-
Type(val) – When evaluating Boolean,integer or float
String(length) value
Array(length) value

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;

// Display array using for loop,foreach loop,print_r,var_dump

Foreach(Arrvar as $value)

{ echo $value}

// It works with elements of array instead of index.

//Indexed array Demo

<?php

$arr=array(11,22,33);

echo "<br> Array:";


print_r($arr);

echo "<br><br>";

var_dump($arr);

$strarr=array("Heena","Reena","Teena");

echo "<br> String Array:";

print_r($strarr);

echo "<br><br>";

var_dump($strarr);

$farr=array(11.4,6.7,8.9);

echo "<br> Double Array:";

print_r($farr);

echo "<br><br>";

var_dump($farr);

$marr=array(100,"Heena",99.8);

echo "<br> Mixed Array:";

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:

1. Detailed information can be stored in multidimensional array.


Demo.php

<?php

# Multi dimensional array

$arr=array(array(101,202,303),array("HTML","CSS","PHP"),

array("HTML"=>2000,"CSS"=>3000,"PHP"=>4000));

print_r($arr);

?>

Array Functions in PHP:

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

2. Inserting element at End /Removing from End of Array:

a. Array_push() –

The array_push() function inserts one or more elements to the end of an


array.
Syntax: array_push($arr,$v1,$v2);
b. Array_pop() -This function removes the last element of the array. Hence it can be used to
remove one element from the end.
Syntax: array_pop($arr);

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

Syntax: int array_shift($arr)

8. array_unshift($arr,$val) -Adds value at starting of Array

Syntax: array array_unshift($arr,$val);

9. Array_search(value,array) : Searches value within array and returns the first


corresponding key if successful else false.

Syntax: int array_search(value,array);

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.

Syntax: array array_reverse($arr);

Note: Can be used with numeric as well as associative array

11. Array_flip($arr) : Interchanges key and values of Associative Array.

Syntax: array array_flip($arr)

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)

Where, $arr: Input Array

Number: Specifies how many entries should be picked up.

<?php

$arr=array(11,22,33,44);

echo "<br>Array is<br>";

print_r($arr);

$key=array_rand($arr);

echo "<br> Key1:",$arr[$key];

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. 

Syntax: array array_pad($arr, total no of eles in new arr, new value);

Ex: $a=array(10,20);

$b=array_pad($a,5,100); // Inserts 100 5 times

Print_r($b);

16. array_chunk() : It splits an array into chunks of new arrays

Syntax: array_chunk($arr, size of each chunk)

<?php

$arr=array(11,22,33,44,55);

Print_r($arr); // chk wid multidimensional

?>

17. array_sum() – Returns sum of all values in given array


Syntax: array_sum($arr);

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

//list($c,$d)=$arr2; Gives Error as array is associative

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

Syntax: Boolean shuffle($arr);

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

echo "<br> Shuffled Array";

print_r($arr1);

$arr2=array("H"=>"HTML","P"=>"PHP");

echo "Array<br>";

print_r($arr2);

shuffle($arr2);

echo "<br> Shuffled Array";

print_r($arr2);
?>
20. Compact() –

i) It is used to create an array using variables.


ii) This function is opposite of extract() function. It creates an associative array
whose keys are variable names and their corresponding values are array values.
iii) This function returns an array with all the variables added to it.
iv) Any string passed as a parameter which does not match with a valid variable
name will be skipped and will not be added to the array.
Syntax: array compact(“var1”,”var2”…);

<?php
$a="Amit";
$b="Bala";
$c="Ceena";
$arr1=compact("a","b","c");
echo "<br>New Array<br>";
print_r($arr1);
?>
21. Array_unique($arr) :

i) Removes duplicate values from array and returns array.


ii) The array_unique() is not intended to work on multi-dimensional arrays.
iii)The keys of the input array are preserved.
Syntax: array 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);
?>

24. Array_intersect() :- Computes intersection of two arrays.

Syntax: array_intersect($arr1,$arr2)

Note: Keys are preserved.

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

function array_union($x, $y)

$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.

Strings can created in 2 different ways

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.

I. Changing Case of String:


1. Ucfirst() : It converts first character of String in Uppercase and remaining all characters
remains unchanged.
Syntax: ucfirst($str)

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)

4. Strtoupper() -It converts whole string to upper case


Syntax: strtoupper($str)

5. Strtolower() – It converts whole string to lowercase

II. Removing Spaces from String:

1. Ltrim()- It removes white spaces in the string from LHS.


Syntax: ltrim($str, $char)
2. Rtrim()- It removes white spaces from the string from RHS.
3. Trim() – It removes white spaces from string from both sides
Syntax: trim($str, $char)
Where $char can be letter or space or any character.

III. String Count Functions: strlen() ,str_word_Count(), substr_count()

1. Strlen : It calculates length of string


Syntax: strlen(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.

Syntax: str_word_Count($str, $val);


Where,
$str:This parameter specifies the string whose words the user intends to count.This is not
an optional parameter.
1. $Val:Its default value is 0.
The parameter can take below values as required:
 0 :It returns the number of words in the string $string.
 1 :It returns an array containing all of the words which are found in the string.
 2 :It returns an associative array with key-value pairs, where the key deifnes the
position of the word in the string and the value is the word itself.

2. substr_count():

i. It count the number of times a substring that occurs in a given string.


ii.
iii. It also searches for the given substring in a given range of the index.
iv. Searching is case-sensitive.\
v. If the (start+length) value specified for search exceeds the size of the
passed string, it returns a warning message to the user.

Syntax: substr_count($str,$substr,$start,$len);

IV. Miscellaneous String Functions:


1. Str_repeat() -It repeats a string for specific number of times.
Syntax: Str_repeat(string,repeat)
2. Strrev() -It reverses given string
Syntax: $str=strrev(str)
3. Str_pad()- It is used to pad or insert some new chars either front or end of string
Syntax: str_pad($str,len,char,pad_type);
Where,
Pad_type has following values:

1. Str_pad_both:
2. Str_pad_left:
3. Str_pad_right:

Str_replace() -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: 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)

5. Strrpos() – It finds the position of the last occurrence of astring in another


string.
6. The var_dump() : It is used to display structured information (type and value)
about one or more variables.
7. Str_shuffle(): It randomly shuffles all characters of string.

Syntax: str_shuffle($str)

8. Str_split() -It converts string into array.

Syntax: str_split(Str,length)

9. similar_text() : It calculates the similarity between two strings. Returns the


number of matching characters of two strings.
Syntax: similar_text(s1,s2,percent);

4. htmlentities() : It converts certain characters of string in HTML entities.

Syntax: htmlentities($str)

Example:

<?php

$str=”<a href=”www.dypiu.ac.in>DYPIU</a>”;

Echo htmlentities($str);

?>

5. strip_tags() – It removes HTML tags from string.


Syntax: strip_tags($str,tag);

V. Decomposing string : Explode() and implode()

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

2. Strcasecmp() -It is case insensitive function that compares two strings

3. Strncmp() -It case-sensitive function which is used to compare first n character of two
strings

Syntax: strncmp(s1,s2,val);

4. Strncasecmp()- It case-insensitive function which is used to compare first n character


of two strings

Syntax: strncmp(s1,s2,val);

Operators for String Comparisons:

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

VII. Manipulating and searching Strings

<?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);*/

$str="HTML/CSS is client side scripting and PHP is server side scripting";


$newstr=str_replace("is","are",$str);
echo "<br><br> New String after replacing:",$newstr;
echo "<br> First occurence of is:",strpos($str,"is");
echo "<br> Last occurence of is:",strrpos($str,"is");
$arr=str_split($str,3); //converts str to array
echo "<br> Array is";
echo "<pre>";
print_r($arr);
echo "</pre>";
$s1="Amit";
$s2="Ajay";
echo"<br>Matching characters:",similar_text($s1,$s2);

?>

You might also like