0% found this document useful (0 votes)
10 views6 pages

Chapter 2.1-2.2-2.3

php

Uploaded by

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

Chapter 2.1-2.2-2.3

php

Uploaded by

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

Chapter 2

Arrays, Functions and Graphics

2.1 Creating and Manipulating Array, Types of arrays-Indexed, Associative and Multi-
dimensional arrays
Array : An array is a special variable, which can hold more than one value at a time. It is a collection
of data values organized as an ordered collection of key-value pairs.

Types of an array :
1. Indexed array or numeric array
2. Associative array
3. Multidimensional array

1. Indexed Array or Numeric Array : It is a collection of elements where each element is having a
numeric key that represents its index position. Index position starts with value 0. Each element is identified
with its index position.
Syntax : $array_var_name=array(value1,value1=2,…,value N);
- array() function is used to create an array which stores all specified values as elements along with
the keys starting from value 0.
Example :
$number=array(1,2,3,4,5);
$fruits=array(“apple”,”banana”,”orange”);
In an indexed array, elements can also be stored with one to one assignment:
Example:
$fruits[0]=”apple”;
$fruits[1]=”banana”;
$fruits[2]=”orange”;

2. Associative Array : It is a collection of elements where each element is having a string type key assigned
to it. It behaves like two column data where first column indicates key value which is used to access array
elements.
Syntax : $array_var_name[‘key’]= value;
Example:
$cost[‘mango’]=”100”;
$cost[‘banana’]=”10”;
$cost[‘orange’]=”50”;
Or it can be done using array function also:
$cost=array(“mango”=>”100”,”banana”=>”10”,”orange”=>”50”);

key Value
mango 100
banana 10
orange 50

3. Multidimensional Array : A multidimensional array is an array containing one or more arrays. It has
more than one dimension in the form of rows and columns. Each array inside multi-dimensional array is
store in row form and its element values are stored in column form.
Syntax: $array_var_name=array(array1(),array2(),…,array N());
Example:
$cars = array (array("Volvo",22,18), array("BMW",15,13), array("Ciaaz",10,15));
Or
$row0 = array("Volvo",22,18);
$row1 = array("BMW",15,13);
$row2 = array("Ciaaz",10,15);
$cars = array($row0, $row1, $row2);
In the above example, first array i.e. row1 is stored in 0th row and “Volvo” value is stored in column 0,22 is
stored in column 1 and 18 is stored in column 2. Next element row1 is stored in 1st row and so on.

Column 0 Column 1 Column 2


Row 0 Volvo 22 18
Row 1 BMW 15 13
Row 2 Ciaaz 10 15

2.3 Traversing Arrays :


Array traversing is the process of accessing elements of an array. The most common way of traversing
through an array is using foreach loop.
Example:
1. Indexed array :
$fruits=array(“apple”,”banana”,”orange”);
foreach($fruits as $fname)
{
echo ($fname);
}

2. Associative array : Traverse using key/value pair


$fruits=array(‘name’=>’Mango’,’cost’=>’100’,’quantity’=>’12’ );
foreach ($fruits as $key=>$value)
{
echo “{$key} ={$value}<br>”;
}

3. Multidimensional array : Traverse using two for loops to indicate row and column position. Each
element has a row position and column position. For example, $car[0][1]- Element at 0th row and 1st column
position in an array car.
$cars = array (array("Volvo",22,18), array("BMW",15,13), array("Ciaaz",10,15));
for($row=0;$row<3;$row++)
{
echo “Row number=$row”;
for($col=0;$col<3;$col++)
{
echo $cars[$row][$col];
}
}

2.2 Extracting data from an array,implode,explode and array flip :


Extracting data from an array :

Copy elements : list() construct is used to copy all array elements into a variable.
Syntax : list ($variable, ...) = $array;
The array’s values are copied into the listed variables in the array’s internal order.
Example :
$student = array("John", 3, "second");
list($name, $rollno, $year) = $student;
echo “$name , $rollno , $year”;
Output: John,3,Second

If you have more values in the array than in the list(), the extra values are ignored.
Example:
$student = array("John", 3, "Second");
list($name, $rollno) = $student;
echo “<br>$name,$rollno”;
Output :John,3

If you have more values in the list() than in the array, the extra values are set to NULL.
Example:
$student = array("John", 3);
list($name, $rollno, $year) = $student;
echo “$name,$rollno,$year”;
Output : John,3,
Copies the data only, doesnt affect the actual array
Slicing an Array : array_slice() function is used to extract only a subset of an array.
Syntax: $subset = array_slice(array_name, offset, length);
- array_slice() function returns a new array consisting of a consecutive series of values from the
original array(array_name).
- offset parameter identifies the initial element to copy (0 represents the first element in the array).
- length parameter identifies the number of values to copy.
The new array has consecutive numeric keys starting at 0.
Example:
$fruits=array("Mango","Banana","Orange","Apple","strawberry");
$set1=array_slice($fruits,2,3);
foreach($set1 as $val)
{
echo "$val &nbsp";
}
Output :Orange Apple strawberry

Removing and Inserting Elements in an Array : The array_splice() function can remove or insert
elements in an array and optionally create another array with removed elements.
Syntax: $new_array= array_splice(array, start [, length [, replacement ] ]);
- new_array is the array variable that stores elements return by function
- array inside round bracket indicates name of the array on which splice operation has to be
performed.
- start parameter is used to indicate starting position from array for extraction
- length specify number of values to be extracted.
- replacement
Example 1 :
$subjects = array("physics", "chem", "math", "bio", "cs", "drama", "classics");
$removed = array_splice($subjects, 2, 3); // math,bio,cs subjects will be removed from array $subjects

Example 2 :
$subjects = array("physics", "chem", "math", "bio", "cs", "drama", "classics");
$removed = array_splice($subjects, 2); // if length is missing then function removes to the end of the array

Example 3 :
array_splice($subjects, 2); // All subjects from index 2 will be removed but does not store in any variable.
Example 4 :
To remove elements from an array and store new values at the location in an array.
$arr1=array("phy","chem","math","bio","CS","Eng"); //original array
$replacearr=array("Mango","Apple","Banana"); // array to be stored at specified position
$newarr=array_splice($arr1,2,1,$replacearr); //It will remove math from original array and add elements
from replacearry in the original array.
echo "Original array :<br> ";
foreach ($arr1 as $val)
{
echo "$val<br>";
}
Output : Original array :
phy chem Mango Apple Banana bio CS Eng

Example 5 :
To insert new elements into the array while pushing existing elements to the right and without deleting any
element from original array , in splice operation mention length as 0.
$arr1=array("phy","chem","math","bio","CS","Eng");
$replacearr=array("Mango","Apple","Banana");
$newarr=array_splice($arr1,2,0,$replacearr);
echo "Original array :<br> ";
foreach ($arr1 as $val)
{
echo "$val &nbsp";
}
Output : Original array :
phy chem Mango Apple Banana math bio CS Eng

Extract () function :
The extract() function perform conversion between arrays and variables. The names of the variables
correspond to keys in the array, and the values of the variables become the values in the array. This function
treats keys as variable names and values as variable values. For each key/value pair it will create a variable
in the current symbol table, subject to flags and prefix parameters.
Syntax : extract ( array &$array , int $flags = EXTR_OVERWRITE , string $prefix = "" )
- Array it is an associative array.
- flags can be one of the following option :
EXTR_OVERWRITE - If there is a collision, overwrite the existing variable.
EXTR_SKIP - If there is a collision, don't overwrite the existing variable.
EXTR_PREFIX_SAME - If there is a collision, prefix the variable name with prefix.
EXTR_PREFIX_ALL - Prefix all variable names with prefix.
EXTR_PREFIX_INVALID - Only prefix invalid/numeric variable names with prefix.
EXTR_IF_EXISTS - Only overwrite the variable if it already exists in the current symbol table.
EXTR_PREFIX_IF_EXISTS - Only create prefixed variable names if the non-prefixed version of
the same variable exists in the current symbol table.
EXTR_REFS - Extracts variables as references.
- string is the variable that returns the number of variables successfully imported into the symbol
table.
Example :
<?php

/* Suppose that $var_array is an array returned from


wddx_deserialize */

$size = "large";
$var_array = array("color" => "blue",
"size" => "medium",
"shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");

echo "$color, $size, $shape, $wddx_size\n";

?>
Output :
blue, large, sphere, medium
The $size wasn't overwritten because we specified EXTR_PREFIX_SAME, which resulted
in $wddx_size being created. If EXTR_SKIP was specified, then $wddx_size wouldn't even have been
created. EXTR_OVERWRITE would have caused $size to have value "medium",
and EXTR_PREFIX_ALL would result in new variables being named $wddx_color, $wddx_size,
and $wddx_shape.

Implode function : It is used to make a single string with all elements of array. It works like a join().
Syntax : $string = implode(separator, array);
- separator is the character to be placed between the elements of array. It is optional. Default
value for separator is “”-an empty string.
- array indicates name of array variable from which elements are taken to make a string.
Example:
$fruits = array('Apple', ‘Banana', 'Orange’);
$str1 = implode(',', $fruits);

Output: a single string str1 containing value as Apple,Banana,Orange

Explode function : It is used to split the data from string into an array of values.
Syntax: $array = explode(separator, string [, limit]);
- separator is a string containing the field separator
- string is the string to split.
- limit, is the maximum number of values to return in the array. If the limit is reached, the last
element of the array contains the remainder of the string. It is an optional attribute.
Example :
$input = 'Fred,25,Wilma';
$fields = explode(',', $input);

Array flip : It is used to exchange all keys with their associated in an array. It flips the order of key-value
pair. After applying flip operation on array, keys from array becomes values and values from array becomes
keys.
Syntax : array_flip ( array $array )
- It returns an array with flip order.
Example :
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$result=array_flip($a1);
print_r($result);
?>
Output:
Array ( [red] => a [green] => b [blue] => c [yellow] => d )

You might also like