Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

PHP Array1

Uploaded by

Anagha Bhattad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

PHP Array1

Uploaded by

Anagha Bhattad
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Web Based Application

development with PHP


WBP (22619)

S. S. Dohe
Lect, Computer Engineering
Government Polytechnic Yavatmal
COMPETENCY
Develop simple web-based application
using PHP language
Unit-II
Arrays, Functions and Graphics
CO
b) Perform operations based on arrays and
graphics.
UO
2 a) Manipulate the given type of arrays to get
the desired result.
Introduction
Introduction
Adding and Deleting Elements
Adding and Deleting Elements
unset () in Arrays:
isset() in Arrays:
Indexed Array
Indexed Array
Indexed Array
Associated Array
Associated Array
Associated Array
Multidimensional Arrays
Multidimensional Arrays
extract() Function

• The extract() Function is an inbuilt function in PHP.

• The extract() function does array to variable conversion.

• That is it converts array keys into variable names and array values into
variable value.
• Syntax:
int extract($input_array, $extract_rule, $prefix)

• Parameters: The extract() function accepts three parameters, out of which


one is compulsory and other two are optional. All three parameters are
described below:

• $input_array: This parameter is required. This specifies the array to use.

• $extract_rule: This parameter is optional. The extract() function checks for


invalid variable names and collisions with existing variable names. This
parameter specifies how invalid and colliding names will be treated.

• $prefix: This parameter is optional. This parameter specifies the prefix. The
prefix is automatically separated from the array key by an underscore
character
Example :
Example :
implode() Function
• The implode() is a built-in function in PHP and is used to join the
elements of an array. implode() is an alias for PHP | join()
function and works exactly same as that of join() function.

• If we have an array of elements, we can use the implode() function to


join them all to form one string.

• We basically join array elements with a string. Just like join() function ,
implode() function also returns a string formed from the elements of
an array.
• Syntax :
string implode(separator,array)

• Parameters: The implode() function accepts two parameter out of


which one is optional and one is mandatory.

• separator: This is an optional parameter and is of string type. The


values of the array will be join to form a string and will be separated
by the separator parameter provided here. This is optional, if not
provided the default is “” (i.e. an empty string).

• array: The array whose value is to be joined to form a string.


Example:
explode() Function

• The explode() function is an inbuilt function in PHP used to split a


string into different strings.

• The explode() function splits a string based on a string delimiter, i.e. it


splits the string wherever the delimiter character occurs.

• This function returns an array containing the strings formed by


splitting the original string.
explode() Function
• Syntax:
explode(separator, string, limit)

Parameters:
• The explode function accepts three parameters of which two are compulsory and one is optional.

• separator: Required. Specifies where to break the string

• Original String: Required. The string to split

• Limit: Optional. Specifies the number of array elements to return.


Possible values:
0 - Returns an array with one element
Greater than 0 - Returns an array with a maximum of limit element(s)
Less than 0 - Returns an array except for the last -limit elements()
Example
array_flip() function

• The array_flip() function is used to exchange the keys with their


associated values in an array.

• The function returns an array in flip order, i.e. keys from array become
values and values from array become keys.

• The values of the array need to be valid keys, i.e. they need to be
either integer or string.
array_flip() function

• Syntax:
array_flip(array)

• Parameter Values

Parameter Description Is compulsory

array Specifies an array of key/value pairs to be compulsory


flipped.
Example : array_flip() function
<?php
$a=array("Orange" => 100, "Apple" => 200, "Banana" => 300, "Cherry" => 400);
$b=array_flip($a);
print_r($b);
?>
Output:
Array ([100] => Orange [200] => Apple [300] => Banana [400] => Cherry )
Traversing Arrays
• The most common task with arrays is to do something with every
element—for instance
• Sending mail to each element of an array of addresses
• Updating each file in an array of filenames
• Adding up each element of an array of prices.

• There are several ways to traverse arrays in PHP, and the one you
choose will depend on your data and the task you’re performing.
o Using a for Loop
o The Iterator Functions
o The foreach Construct
Using a for Loop
• for loop: Entry control loop:

PHP engine executes statement(s) inside the for loop, until the given conditional
expression evaluates to false.

Syntax:
for(initialization; conditional expression; increment/decrement)
{
statement(s);
}

OR

for(initialization; conditional expression; increment/decrement):


statement(s);
endfor;
Using a for Loop
• Ex:
for( $counter=0; $counter<5; $counter++ )
{
echo "Hello World","<br/>";
}

OR

for( $counter=0; $counter<5; $counter++ ):


echo "Hello World","<br/>";
endfor;

Note: When you know exactly how many # of times the loop is going
to get execute, use for loop.
PHP Array Iterator Functions
• PHP Array Iterative functions can be used to access the elements as :
• first element,
• last element,
• previous element or
• next element
• The concept of pointers is used here.

• When an array is created a hidden array pointer stores the address of first
element by default.

• When any of iterative functions is called that action is performed on array and an
element is returned.

• PHP array iterative functions treat array as a doubly linked list of similar values.
Each element has direct access to the next and previous element.
Types of PHP Array Iterator Functions

1. current()
• Current() function returns the value of the element whose address is currently
stored in the array pointer.
• Syntax:

• $varName=current($arrayName);

• $varName is the name of the variable that accepts the output of the current
function.

• $arrayName is the name of the array in which you want access the current
element.

• The array pointer is not updated after the current function is called.
Types of PHP Array Iterator Functions
2. next ()
• next() function first updates the array pointer with the address of the next
element. It is relative to the address of the current element. It then returns the
value of this element.
• Syntax:
• $varName=next($arrayName);

• $varName is the name of the variable that accepts the output of the next
function.
• $arrayName is the name of the array from which you want to get the next
element relative to the current pointer.
• The array pointer is updated after the next function is called.
• If the array pointer reaches the end of array and the next function is called array
pointer stays at the last element.
Types of PHP Array Iterator Functions
3. prev ()
• prev() function updates the array pointer with the address of previous element. It is
relative to address of the current element. It then returns the value of this newly located
element.
• Syntax:
• $varName=prev($arrayName);

• $varName is the name of the variable that accepts the output of the prev function.

• $arrayName is the name of the array from which you want to read the previous element
relative to the current pointer.

• The array pointer is updated when the prev () function is called.


• If the array pointer reaches the beginning of array and prev() function is called, array
pointer stays at the first element of the array.
Types of PHP Array Iterator Functions
4. reset ()
• reset() function updates the array pointer with the address of the first element of
the array. It then returns the value of the first element.

• Syntax:
• $varName=reset($arrayName);

• $varName is the name of the variable that accepts the output of reset function.

• $arrayName is the name of the array in which you want to reach to the first
element.

• The array pointer is updated when the reset function is called.


Types of PHP Array Iterator Functions
5. end ()
• end() function updates the array pointer with the address of the last element of
the array. It then returns the value of the last element.

• Syntax:
• $varName=last($arrayName);

• $varName is the name of the variable that accepts the output of end function.

• $arrayName is the array in which you want to move the array pointer to last
element.

• The array pointer is updated when the end function is called.


Types of PHP Array Iterator Functions

• each(): Returns the key and value of the current element as an array
and moves the iterator to the next element in the array

• key(): Returns the key of the current element


Types of PHP Array Iterator Functions
• Example Code

<?php $arrVals=array(30,23,59,93,50,11); Output :


print_r($arrVals);
echo "<h3> PHP array Iteration functions</h3>";
echo "<br>current->".current($arrVals)."<br>";
echo "next->".next($arrVals)."<br>";
echo "next->".next($arrVals)."<br>";
echo "next->".next($arrVals)."<br>";
echo "prev->".prev($arrVals)."<br>";
echo "end->".end($arrVals)."<br>";
echo "reset->".reset($arrVals)."<br>";
?>
The foreach Construct
• The foreach loop is used to traverse the array elements.
• foreach works only on arrays and objects, and will issue an error when you try to use it on a
variable with a different data type or an uninitialized variable.
• This allows you to run blocks of code for each element.

• Syntax of PHP foreach():


• Syntax1:

foreach($arrayName as $variableName)
{
statement(s);
}

OR

foreach($arrayName as $variableName):
statement(s);
endforeach;
The foreach Construct
• Syntax2:

foreach($arrayName as $key => $value)


{
statement(s);
}
OR
foreach($arrayName as $key => $value):
statement(s);
endforeach;
The foreach Construct
• Example Code:

<!DOCTYPE html>
<html>
<body>

<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $x) {
echo "$x <br>";
} Output:
?> red
</body> green
</html> blue
yellow
The foreach Construct
• Example Code:
<!DOCTYPE html>
<html>
<body>
<?php
$fruits = array(
"Apple" => "red",
"banana" => "yellow",
"orange" => "orange"
);
foreach ($fruits as $key => $value) {
echo "The color of the ". $key . " is " . $value . "<br>"; }
?>
</body>
</html>
Functions
• PHP function is a piece of code that can be reused many times.
• It can take input as argument list and return value.
• There are thousands of built-in functions in PHP.
• Code Reusability: PHP functions are defined only once and can be
invoked many times, like in other programming languages.
• Less Code: It saves a lot of code because you don't need to write the
logic many times. By the use of function, you can write the logic only
once and reuse it.
• Functions save on compile time—no matter how many times you call
them, functions are compiled only once for the page.
• Functions in a PHP program can be built-in or user-defined
Functions
• To define a function, use the following syntax:

function function_name([parameter[, ...]])


{
statement list
}
• The function name can be any string that starts with a letter or
underscore followed by zero or more letters, underscores, and
digits.
• Function names are case-insensitive.
• By convention, built-in PHP functions are called with all lowercase.
Types of Functions

1. user-defined Functions

2. Variable Functions

3. Anonymous Functions

You might also like