0% found this document useful (0 votes)
25 views31 pages

arrays(2)

This document provides an overview of arrays in PHP, including their types (indexed, associative, and multidimensional) and how to create and manipulate them. It explains key functions such as count(), extract(), implode(), and explode(), along with examples of how to loop through arrays using for and foreach constructs. Additionally, it covers the concept of traversing arrays and using iterator functions to manage array elements.

Uploaded by

bansalhemant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views31 pages

arrays(2)

This document provides an overview of arrays in PHP, including their types (indexed, associative, and multidimensional) and how to create and manipulate them. It explains key functions such as count(), extract(), implode(), and explode(), along with examples of how to loop through arrays using for and foreach constructs. Additionally, it covers the concept of traversing arrays and using iterator functions to manage array elements.

Uploaded by

bansalhemant
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

UNIT2

Arrays, functions
and graphics
arrays
 An array stores multiple values in one
single variable:
 Example
 <?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . "
and " . $cars[2] . ".";
?>
What is an Array?
 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.
Create an Array in PHP

 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


 Get The Length of an Array - The count()
Function
 The count() function is used to return the
length (the number of elements) of an
array:
 Example
 <?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
 Output - 3
1PHP Indexed Arrays

 There are two ways to create indexed arrays:


 The index can be assigned automatically
(index always starts at 0), like this:
 $cars = array("Volvo", "BMW", "Toyota");
 or

 the index can be assigned manually:


 $cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
 The following example creates an
indexed array named $cars, assigns three
elements to it, and then prints a text
containing the array values:
 Example
 <?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . "
and " . $cars[2] . ".";
?>
 Output-I like Volvo, BMW and Toyota.
 Loop Through an Indexed Array
 To loop through and print all the values of an
indexed array, you could use a for loop, like this:
 Example
 <?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {


echo $cars[$x];
echo "<br>";
}
?>
 Output-
 Volvo
BMW
Toyota
2PHP Associative Arrays
 Associative arrays are arrays that use
named keys that you assign to them.
 There are two ways to create an
associative array:
 $age = array("Peter"=>"35",
"Ben"=>"37", "Joe"=>"43");
 or:
 $age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
 The named keys can then be used in a
script:
 Example

 <?php

$age= array("Peter"=>"35", "Ben"=>"37


",
"Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years
old.";
?>
 Output-Peter is 35 years old.
 Loop Through an Associative Array
 To loop through and print all the values of an associative
array, you could use a foreach loop, like this:
 Example
 <?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value)


 {
echo "Key=" . $x . , "Value=" . $x_value;
echo "<br>";
}
?>

 Output
 Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
3PHP Multidimensional Arrays

 A multidimensional array is an array


containing one or more arrays.
 PHP supports multidimensional arrays
that are two, three, four, five, or more
levels deep. However, arrays more than
three levels deep are hard to manage for
most people.
 PHP - Two-dimensional Arrays
 A two-dimensional array is an array of
arrays
 First, take a look at the following table:

Name Stock Sold


Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15
 We can store the data from the table above
in a two-dimensional array, like this:
 $cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
 Now the two-dimensional $cars array
contains four arrays, and it has two indices:
row and column.
 To get access to the elements of the $cars
array we must point to the two indices (row
and column):
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $cars = array (
 array("Volvo",22,18),
 array("BMW",15,13),
 array("Saab",5,2),
 array("Land Rover",17,15)
 );

 echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";


 echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
 echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
 echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
 ?>

 </body>
 </html>
 Output
 Volvo: In stock: 22, sold: 18.
BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.
Array extract ()function
 The extract() function imports variables
into the local symbol table from an array.
 This function uses array keys as variable
names and values as variable values. For
each element it will create a variable in
the current symbol table.(array to
variable conversion)
 This function returns the number of
variables extracted on success.
 Syntax
 extract(array, extract_rules, prefix)
PHP extract() Function
in array
 <html>
 <body>
 <?php
 $a = "Original";
 $my_array = array("a" => "Cat","b" => "Dog", "c" =>
"Horse");
 extract($my_array);
 echo "\$a = $a; \$b = $b; \$c = $c";
 ?>
 </body>
 </html>
 Output:
$a = Cat; $b = Dog; $c = Horse
PHP array_flip() Function
 Flips/Exchanges all keys with their associated values
in an array
 <html>
 <body>
 <?php
 $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"
=>"yellow");
 $result=array_flip($a1);
 print_r($result);
 ?>
 </body>
 </html>
 Output
 Array ( [red] => a [green] => b [blue] => c [yellow]
=> d )
Traversing array
 Traversing an array means to visit each
and every element of array using a
looping structure and iterator function
 Several ways to traverse array in php
 1)Using foreach construct
 2)Using for loop
 3)Using Iterator function
1)The foreach Construct:- The most common way
to loop over elements of an array is to use the
foreach construct: Syntax
foreach($array as $value){ statement }

$a=array(‘aaa’,’bbb’,’ccc’);
foreach($a as $value)
{
Echo “$value\n”;
}
Output:
aaa
bbb
ccc
1)Associative array example
Syntax
foreach($array as $value){ statement }

$age=array(‘raj’=>1, ’simran’=>2);
foreach($age as $key=> $value)
{
Echo “$key rollno is $value \n”;
}
Output:
raj rollno is 1
simran rollno is 2
 2) Using a for Loop
 if you know that you are dealing with an indexed

array, where the keys are consecutive integers


beginning at 0, you can use a for loop to count
through the indexes. Here's how to print an array
using for:
$a = array(1,2,3,4);
for($i = 0; $i < count($a); $i++)
{
$value = $a[$i];
echo "$value\n"; }
Output
1
2
3
4
 3) The Iterator Function
 Every PHP array keeps track of the current element you're
working with; the pointer to the current element is known
as the iterator. PHP has functions to set, move, and reset
this iterator. The iterator functions are:
 current( ) Returns the element currently pointed at by the
iterator
 reset( ) Moves the iterator to the first element in the array
and returns it
 next( ) Moves the iterator to the next element in the array
and returns it
 prev( ) Moves the iterator to the previous element in the
array and returns it
 end( ) Moves the iterator to the last element in the array
and returns it
 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
Pointer
 $a=array[“sanjay”,”Aman”,”rehman”];
 echo current($a); ==sanjay
 echo next($a); =Aman
 echo prev($a); ==> sanjay
 echo end($a); ==> rehman
 echo reset($a); ==> sanjay

 Echo key($a); 0
 Print_r(each($a)); output
 Array (
 [key]>>0
 [value]>>sanjay
PHP implode() Function

 the implode() function returns a string


from the elements of an array.
 Note: The implode() function accept its
parameters in either order. However, for
consistency with explode(), you should use
the documented order of arguments.
 Note: The separator parameter of
implode() is optional. However, it is
recommended to always use two
parameters for backwards compatibility.
 Note: This function is binary-safe.
 Syntax
 implode(separator,array)
 Parameter Values
 Parameter Description
 Separator- Optional. Specifies what
to put between the array elements.
Default is "" (an empty string)
 Array- Required. The array to join to a
string
 <DOCTYPE html>
 <html>
 <body>

 <?php
 $arr = array('Hello','World!','Beautiful','Day!');
 echo implode(" ",$arr)."<br>";
 echo implode("+",$arr)."<br>";
 echo implode("-",$arr)."<br>";
 echo implode("X",$arr);
 ?>
Output
Hello World! Beautiful Day!
 </body> Hello+World!+Beautiful+Day!
 </html> Hello-World!-Beautiful-Day!
HelloXWorld!XBeautifulXDay!
PHP explode() Function
 the explode() function breaks a string
into an array.

 Note: The "separator" parameter cannot


be an empty string.

 Syntax
 explode(separator,string,limit)
Parameter Description
separator Required. Specifies where to break the string
string Required. The string to split
limit Optional. Specifies the number of array elements to
return.Possible values:
•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()
•0 - Returns an array with one element
 <!DOCTYPE html>
 <html>
 <body>

 <?php
 $str = "Hello world. It's a beautiful day.“;
 print_r (explode(" ",$str));
 ?>

 </body>
 </html>
 Output
 Array ( [0] => Hello [1] => world. [2] => It's
[3] => a [4] => beautiful [5] => day.

You might also like