W WITH PHP A F - WordPress.com...3.1.1 C REATING A RRAYS | In PHP, the array() function is used to...

Preview:

Citation preview

WORKING WITH PHP ARRAYS

AND FUNCTIONS Unit - III 1

SYLLABUS

3.1 Array: Types of Array, Arrays definition, Creating arrays; using arrays() function, using Array identifier, defining start index value, adding more elements to array,

3.2 Associative arrays, key-value pair, using for-each statement to go through individual element with loop.

3.3 Functions: defining a user defined function, calling function, returning values from function, Variable scope, Accessing variables with global statement,

3.4 Setting default values for arguments, passing with values and passing with reference,

3.5 Working with string, Dates and Time functions, common mathematical functions. 2

3.1 ARRAYS

An array stores multiple values in one single variable.

An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

$cars1 = "Volvo"; $cars2 = "BMW"; $cars3 = "Toyota";

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The solution is to create an array!

An array can hold many values under a single name, and you can access the values by referring to an index number.

3

3.1.1 CREATING ARRAYS

In PHP, the array() function is used to create an

array:

array( );

In PHP, there are three types of arrays:

Indexed arrays - Arrays with a numeric index

Associative arrays - Arrays with named keys

Multidimensional arrays - Arrays containing one

or more arrays

4

3.1.2 USING ARRAY( ) FUNCTION

In PHP, the array() function is used to create an array:

array( );

Syntax:

$ArrayName = array(value1,value2….valueN);

In Numeric array each elements are assigned a numeric key value starting from 0 for first elements and so on.

Example:

<?php

$name=array(“Arpan”, “Soham”, “Helisha”); print_r($name);

?>

Output:

Array([0] =>Arpan [1] =>Soham [2]=>Helisha) 5

3.1.3 USING ARRAY IDENTIFIER

In PHP, we can also create an array using array

identifier.

Syntax:

$ArrayName [ ] = “value”; Example:

<?php

$name[ ] = “Arpan”; $name[ ] = “Soham”; $name[ ] = “Helisha”; print_r($name);

?>

Output:

Array([0] =>Arpan [1] =>Soham [2]=>Helisha) 6

3.1.4 DEFINING START INDEX VALUE

By default starting index of an array is 0.

It is incremented by 1 for each successive

elements of an array.

But it is also possible to define start index of an

array.

Example:

<?php

$name = array(19=> “Arpan”, “Charmi”, “Deep”); print_r($name);

?>

Output

Array ([19]=> Arpan [20]=>Charmi [21]=>Deep)

7

3.1.5 ADDING MORE ELEMENTS TO ARRAY

Once an array id created we can add more elements

to an array using array identifier.

Example:

<?php

$name=array(“Arpan”, “Soham”, “Helisha”); print_r($name);

echo “<br>”; $name[ ] = “Shivani”; print_r($name);

?>

Output:

Array([0] =>Arpan [1] =>Soham [2]=>Helisha)

Array([0] =>Arpan [1] =>Soham [2]=>Helisha [3]=>Shivani)

8

3.2 ASSOCIATIVE ARRAYS

In associative array each elements having key associated with it.

It can be either numeric or string.

Syntax:

$ArrayName = array( Key1=>Value1, Key2=>Value2, …, KeyN=>ValueN)

In PHP, if we don’t specify key value for each element then it will create a numeric array.

Example (Numeric Key): <?php

$name = array(19=> “Arpan”, 20=>“Charmi”); print_r($name);

?>

Output Array ([19]=> Arpan [20]=>Charmi)

9

Example (String Key):

<?php

$marks = array(“JAVA”=> 25, “DWPD”=>30); print_r($marks);

?>

Output

Array ([JAVA]=> 25 [DWPD]=>30)

10

3.3 FUNCTIONS

A function is a block of statements that can be

used repeatedly in a program.

A function will not execute immediately when a

page loads.

A function will be executed by a call to the

function.

11

3.3.1 CREATE A USER DEFINED FUNCTION IN

PHP A user defined function declaration starts with the word

"function“. Syntax

function functionName()

{ code to be executed; }

Note: A function name can start with a letter or underscore (not a number).

Example

<?php function writeMsg( )

{ echo "Hello world!"; } writeMsg(); // call the function ?>

12

3.3.2 CALLING A FUNCTION

In PHP, function is called using FunctionName

and its argument value.

Syntax:

FunctionName(Argument-Value or Varibale Name);

Example:

<?php

function writeMsg( )

{

echo "Hello world!";

}

writeMsg( ); // call the function

?>

13

3.3.3 RETURN A VALUE FROM FUNCTION

In PHP, function can return a single value using return statement to the point from which the function is called.

Example

<?php function sum($x, $y)

{ $z = $x + $y; return $z; } echo "5 + 10 = " . sum(5, 10) . "<br>"; echo "7 + 13 = " . sum(7, 13) . "<br>"; echo "2 + 4 = " . sum(2, 4); ?>

14

3.3.4 VARIABLE SCOPE

A variable that is declared inside the function is

called as local variable.

It can be accessed only within the function in which

it is declared.

We can not access the local variables from outside

that function.

A variable that is declared outside all the function

are known as global variable.

But in PHP, to access the global variable inside the

function we need to declare them using global

keyword.

Syntax:

global $variableName;

15

Example:

<?php

$mid=15;

$gtu = 45;

$total;

function TotalMarks( )

{

global $mid, $gtu, $total;

$total = $mid + $gtu;

}

TotalMarks( );

echo “Total Marks = $total”; ?>

Output: Total Marks = 60

16

3.3.5 DEFAULT ARGUMENTS

In PHP, default argument in function must be assign some value to the argument while defining it.

Default arguments must be written from right to left direction.

Syntax:

funtion functionName( $argument1, #argument2=Value)

{

Function Body

}

Example

<?php function total($a, $b = 50)

{ echo “Total = $a + $b<br>"; } total(350); total(10,65);

?> 17

3.4 CALL BY VALUE

When we pass arguments to the function, the

values of the passed arguments are copied into

argument variables declared inside the argument

list of function definition.

So, called function works with copies of

argument instead of original passed arguments.

So any changes made to these variables in the

body of the function are local to that function and

are not reflected outside it.

18

Example

<?php

function addSix($num)

{

$num += 6;

}

$orignum = 10;

addSix( $orignum );

echo "Original Value is $orignum<br />";

?>

Output

Original Value is 10

19

3.4.1 CALL BY REFERENCE

It is possible to pass arguments to functions by

reference.

This means that a reference to the variable is

manipulated by the function rather than a copy

of the variable's value.

Any changes made to an argument in these cases

will change the value of the original variable.

You can pass an argument by reference by

adding an ampersand to the variable name in

either the function call or the function definition.

20

Example

<?php

function addSix(&$num)

{

$num += 6;

}

$orignum = 10;

addSix( $orignum );

echo "Original Value is $orignum<br />";

?>

Output

Original Value is 16

21

3.5 STRING FUNCTIONS

String functions are used to manipulated strings.

chr( )

This function accepts ASCII value as an argument

and returns a character code.

Syntax:

chr(ASCII Value)

Example:

<?php

echo chr(97);

?>

Output

a

22

ord( )

This function accepts a string as an argument and

returns the ASCII value of the first character of a

string.

Syntax

ord(string)

Example

<?php

echo ord(“VPMP”); echo “<br>”; echo ord(“V”); ?>

Output

86

86

23

strtolower( )

This function accepts a string as an argument and

coverts all the characters of the string into lowercase

letters.

Syntax

strtolower(string);

Example

<?php

echo strtolower(“VPMP”); ?>

Output

vpmp

24

strtoupper( )

This function accepts a string as an argument and

coverts all the characters of the string into uppercase

letters.

Syntax

strtoupper(string);

Example

<?php

echo strtoupper(“vpmp”); ?>

Output

VPMP

25

strlen( )

This function accepts a string as an argument and

returns the number of character of a string.

Syntax

strlen(string)

Example

<?php

echo strlen(“VPMP”); ?>

Output

4

26

ltrim( )

This function accepts a string as an argument and

removes white spaces from the left side of the string.

Syntax

ltrim(string)

Example

<?php

echo ltrim(“ VPMP”); ?>

Output

VPMP (Without any leading whitespace)

27

rtrim( )

This function accepts a string as an argument and

removes white spaces from the right side of the string.

Syntax

rtrim(string)

Example

<?php

echo rtrim(“VPMP ”); echo (“ Polytechnic”); ?>

Output

VPMP Polytechnic

28

trim( )

This function accepts a string as an argument and

removes white spaces from both side of the string.

Syntax

trim(string)

Example

<?php

echo trim(“VPMP ”); echo trim(“ Polytechnic”); ?>

Output

VPMPPolytechnic

29

substr( ) This function accepts a string as an argument and returns specific

part of the string.

Syntax

substr(string, start [,length])

Start has three values. If it is 0 it means staring from first character of the string. If it is Positive number then starting from specified position from beginning of the string. If it is negative number then staring from specified position from ending of the string.

Example

<?php

echo substr(“VPMP Polytechnic”,2,6); echo substr(“VPMP Polytechnic”,2); echo substr(“VPMP Polytechnic”,-6,2);

?>

Output

PMP Po

PMP Polytechnic

ec 30

strcmp( )

This function accepts two string as an argument and compare that strings. It performs case sensitive comparison.

It returns 0 if the two string are equal.

It returns positive number if string1 is greater than string2.

It returns negative number if string1 is less than string2.

Syntax

strcmp(string1,string2)

Example

<?php

if strcmp(“VPMP”, “vpmp”) {

echo “Both the string are different”; }

?>

Output

Both the string are different 31

strpos( )

This function accepts two string as an argument and

returns the position of the first occurrence of a search

string inside another string.

It performs case sensitive search.

Syntax

strpos(string1, string2);

Example

<?php

echo strpos(“VPMP Polytechnic”, “Polytech”); ?>

Output

6

32

str_replace( )

This function accepts a string as an argument and replaces

specified characters of the sring with another specified

characters.

It returns an integer value indicating number of

replacement occurs in the specified string.

It performs case sensitive replacement operation.

Syntax

str_replace(searchchar, replacechar, string, occurrence);

Example

<?php

echo str_replace(“VPMP”, “LDRP”,”VPMP Polytechnic”); ?>

Output

LDRP Polytechnic

33

strrev( )

This function accepts a string as an argument and

reverse that string.

Syntax

strrev(string);

Example

<?php

echo strrev(“VPMP Polytechnic”); ?>

Output

cinhcetyloP PMPV

34

3.5.1 MATHEMATICAL FUNCTIONS

Math function are used to perform various operations on numeric values.

abs( )

This function is used to returns the absolute value of a number specified as an argument.

Syntax

abs(number);

Example

<?php

echo abs(-10):

echo abs(10):

?>

Output

10

10

35

ceil( )

The ceil() function rounds a number UP to the

nearest integer, if necessary.

Syntax

ceil(number);

Example

<?php

echo (ceil(5.1)) ;

?>

Output

6

36

floor( )

The floor() function rounds a number DOWN to the

nearest integer, if necessary.

Syntax

floor(number);

Example

<?php

echo (floor(5.1)) ;

?>

Output

5

37

round( )

The round() function rounds a floating-point number.

Syntax

round(number, precision);

Number specifies the value to round.

Precision specifies the number of decimal digits to round to. Default is 0

Example

<?php

echo(round(0.60) “<br>”); echo(round(0.49) . "<br>");

?>

Output

1

0 38

fmod( )

The fmod() function returns the remainder (modulo) of x/y.

Syntax

fmod(x,y);

x specifies the dividend.

y specifies the divisor.

Example

<?php $x = 7; $y = 2; $result = fmod($x,$y); echo $result;

?>

Output

1

39

max( )

The max() function returns the highest value in an array, or the highest value of several specified values.

Syntax

max(array_values); or

max(value1,value2,...);

Example

<?php echo(max(2,4,6,8,10) . "<br>"); echo(max(array(4,20,8,10)) . "<br>"); ?>

Output

10

20 40

min( )

The min() function returns the lowest value in an array, or the highest value of several specified values.

Syntax

min(array_values); or

min(value1,value2,...);

Example

<?php echo(min(2,4,6,8,10) . "<br>"); echo(min(array(4,20,8,10)) . "<br>"); ?>

Output

2

4

41

sqrt( )

The sqrt() function returns the square root of a number.

Syntax

sqrt(number);

Example

<?php echo(sqrt(1) . "<br>"); echo(sqrt(9) . "<br>"); echo(sqrt(0.64) . "<br>"); echo(sqrt(-9)); ?>

Output

1

3

0.8

NAN

42

pow( )

The pow() function returns x raised to the power of y.

Syntax

pow(x,y);

x specifies the base to use.

y specifies the exponent.

Example

<?php

echo(pow(2,4) . "<br>");

echo(pow(-2,4) . "<br>");

?>

Output

16

16

43

rand( )

The rand() function generates a random integer.

Syntax

rand();

or rand(min,max);

min specifies the lowest number to be returned. Default is 0.

max specifies the highest number to be returned.

Example

<?php echo(rand() . "<br>"); echo(rand() . "<br>"); echo(rand(10,100)); ?>

Output

7434 7345 14

44

DATE AND TIME FUNCTION

The date functions allow you to display, format and manipulate the date and time on the server.

date( ) The PHP date() function formats a timestamp to a more

readable date and time.

Syntax

date(format,timestamp)

Example

<?php echo "Today is " . date("Y/m/d") . "<br>"; echo "Today is " . date("Y.m.d") . "<br>"; echo "Today is " . date("Y-m-d") . "<br>"; echo "Today is " . date("l"); ?>

Ouput

Today is 2015/08/31 Today is 2015.08.31 Today is 2015-08-31 Today is Monday 45

mktime( )

The mktime() function returns the Unix timestamp for a date.

The Unix timestamp contains the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.

Syntax

mktime(hour,minute,second,month,day,year)

Example

<?php $d=mktime(11, 14, 54, 8, 12, 2014); echo "Created date is " . date("Y-m-d h:i:sa", $d); ?>

Output

Created date is 2014-08-12 11:14:54am 46

time( )

The time() function returns the current time in the

number of seconds since the Unix Epoch (January 1 1970

00:00:00 GMT).

Syntax

time( );

Example

<?php

$t=time();

echo($t . "<br>");

echo(date("Y-m-d",$t));

?>

Output

1440996289

2015-08-31 47

checkdate( )

The checkdate() function is used to validate a Gregorian date.

Syntax

checkdate(month,day,year);

Example

<?php var_dump(checkdate(12,31,-400)); echo "<br>"; var_dump(checkdate(2,29,2003)); echo "<br>"; var_dump(checkdate(2,29,2004)); ?>

Output

bool(false) bool(false) bool(true)

48

getdate( )

The getdate() function returns date/time information of a

timestamp or the current local date/time.

Syntax

getdate(timestamp);

Example

<?php

print_r(getdate());

?>

Output

Array ( [seconds] => 40 [minutes] => 47 [hours] => 0

[mday] => 31 [wday] => 1 [mon] => 8 [year] => 2015 [yday]

=> 242 [weekday] => Monday [month] => August [0] =>

1440996460 ) 49

50

Recommended