0% found this document useful (0 votes)
15 views26 pages

PHP Arrays: Indexed & Associative Types

An array is used to store student data including enrollment number, name, semester, and percentage for 3 students. A table is output on a web page to display this data with the columns labeled enrollment number, name, semester, and marks. The array data is looped through and each element is output to the corresponding table cell.

Uploaded by

Jayaprasanna
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)
15 views26 pages

PHP Arrays: Indexed & Associative Types

An array is used to store student data including enrollment number, name, semester, and percentage for 3 students. A table is output on a web page to display this data with the columns labeled enrollment number, name, semester, and marks. The array data is looped through and each element is output to the corresponding table cell.

Uploaded by

Jayaprasanna
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

2.

12 Arrays
• Arrays is a collection of similar type of elements
but in PHP you can have the elements of mixed
type together in single array.
• In each PHP, each element has two parts key and
value.
• The key represents the index at which the value
of the element can be stored.
• The keys are positive integers that are in
ascending order.
2.12.1 Array Creation
<html >
• In PHP there are two
<head>
types of arrays –
<title> PHP Indexed Arrays<
– Indexed array
/title >
– Associated array
</head>
• Indexed array : Indexed <body>
array are the arrays <?php
with numeric index. The $names = array("AAA", "BBB",
array values can be "CCC");
stored from index 0 . // Printing array structure
print _r($names);
?></body></html>
• Here values gets stored at
corresponding index as
follows -
• $mylist[O]= 10;
• $mylist[l] =20;
• $mylist[2] =30;
• $mylist[3] =40;
• $mylist[4] =50;
• We can directly assign some
value at specific index.
• $mylist[5] = 100;
• 2. Associated array : <html >
<head>
Associated arrays are
<title>PHP Associative Array</title>
the arrays with named </head>
keys. It is a kind of array <body>
with name and value <?php
pair. $city["AAA"]= "Pune";
$city["BBB"]= "Mumbai"; .
$city["CCC"]= "Chennai";
// Printing array structure
print_r($city);
?>
</body>
</html>
2.12.2 Accessing Array Elements
• Using an array subscript we can access the array element. The
value of subscript is enclosed with in the square brackets. For
example -
• $Citycode['Pune'] = 005;
• $Name[O]="Chitra";
• Multiple values can be set to a single scalar variableusing array.
For example -
• $people= array("Meena","Teena","Heena");
• list($operator,$accountant,$manager)=$people;
• By this assignment Meena becomes operator, Teena becomes
accountant and Heena becomes the manager.
• Ex. 2.12.1 Consider an associative array called
person_age with name and age of 10
persons. Write a PHP program to calculate
the average age of this associative array AU
<html > // Printing array structure
<head> $sum =array_sum($person
<title>PHP Associative _age);
Array</title> print("The sum of all the ages
</head> is $sum");
<body> $avg=$sum/10;
<?php print("<br/>The average is
$person _age =array('AAA' $avg");
=>10,'BBB' =>22,'CCC' =>
45,'DDD'=> 31,'EEE' =>33,'FFF'
?></body></html>
=>25,'GGG' =>56,'HHH' output: the sum of all age is
=>73,'Ill' = > 35,'JJJ' =>47); 377 The average is 37.7
2.12.3 Functions for Dealing with Arrays

<?php
$mylist=array(10,20,30,40,
50);
unset($mylist [1]);
for($i=0;$i < =4;$i + +)
{
print $mylist[$i];
print “ “ ;
}?>
• The functions array_keys and array_values are used to return
the array keys and the values at corresponding key. For
example consider the following PHP document
<?php
$mylist=array(10= > "AAA",20 = >"BBB",30= > "CCG',40= >"DDD",50=
>"EEE");
$Roll = array _keys ($mylist);
$Name = array_ values($mylist);
Print_r($Roll);
print "<br/>";
print_r($Name);
?>
• The existence of particular key can be checked by
using the array_key_exists function. This
functionreturns the Boolean value.
• The is_array returns the Boolean value. This
function takes a variable as a parameter. If the
function returns TRUE then that means the
parameter passed to this function is of array type
• The implode and explode functions are used to
break the word into strings or vice versa.
<?php $newSentence="I Like Programming
$mylist = In It";
array("Hello","PHP","You","Are"," $chunks =explode(" ",$newSentence);
Wonderfull!!!"); echo "The new sentence =
$mySentence = implode(" ", $mylist); $newSentence";
for($i = 0; $i < count($mylist); $i+ +) print "<br/>";
{ echo "The first chunk= $chunks[0]";
echo "$i = $mylist[$i] <br />"; print "<br/>";
} echo "The second chunk=$chunks[l]";
echo "The sentence is = print "<br/>";
$mySentence <br />"; echo "The third chunk=$chunks[2]";
print "<hr/>"; print "<br/>";
?>
Output
Sequential Access to Array Elements

• The array element reference start at the first


element and every array maintains an internal
pointer using which the next element can be
easily accessible. This helps to access the array
elements in sequential manner.
• The pointer current is used to point to the
current element in the array. Using the next
function thenext subsequent element can be
accessed.
<?php $myval= next ($mylist);
$mylist = print("The next value of the array
array("Hello","PHP","You","Are is <b>$myval</b>");
","Wonderful!!!"); print "<br/>";
$myval=current($mylist); $myval= next($mylist);
print("The current value of the print("The next value of the array
array is <b>$myval</b>"); is <b>$myval</b>");
print "<br/>": print "<br/>";
$myval=:next($mylist); $myval= next($mylist);
print("The next value of the array print("The next value of the array
is <b>$myval</b>"); is <b>$myval</b>");
print "<br/>"; ?>
<?php
$mylist =
array("Hello","PHP","You",
"Are","Wonderful!!!");
while($myval =each($mylist))
{
$val=$myval["value"];
print "<br/>";
}
?>
• For each function is used to <?php
iterate through all the $mylist = array(“Hello",
elements of the loop. "PHP","You","Are","Wonderful!
• The syntax of for each !!");
statement is as follows - foreach($mylist as $value)
foreach($array as $value) {
{ print("The current value of the
statements to be executed array is
} <b>$value</b>");
• The above code can be print "<br/>";
modified and written as }?>The output will be the same
follows - as above.
Sorting Arrays
• Sorting is a process in which the elements of arrays in
some specific order. There are two types ordering
which are followed in sorting - ascending order and
descending order.
• Basically PHP uses sort function for sorting the array
elements. There are some other functions that are
also available for sorting the arrays in desired manner.
• The sort function sorts the array based on the values.
After applying the sort function this function assigns
new keys to the values of the array.
• <?php
• $A = array("A" = > "Supriya", "B"= >
"Monika","C"= >"Kumar","D"=
>"Archana"):
• print "<b> Original Array: <b><br/>";.
• foreach($A as $key = > $value )
• print(" [$key] = >$value <br />");
• sort($A);
• print "<br/>";
• print "<b>Sorted Array:<b><br/>";
• foreach($A as $key= >$value)
• print("[$key] = >$value <br />");
• ?>
• The asort ( ) function sorts all array by the
values. But the original keys are kept.
• The ksort function sorts the array by keys but
each value's original key is retained.
• <?php • print "<,hr/>";
• $A = array("A"=> "Supriya", "B"=> • $B = array(30 => "CCC", 20 =>
"Monika","C"=> "BBB", 40 => "DDD",lO=>"AAA");
"Kumar","D"=>"Archana"); • print "<b>Original Array:<b><br/>";
• print "<b>Original • foreach($A as $key = > $value )
Array:<b><br/>"; • print(" [$key] = >$value <br I>");
• foreach($A as $key = > $value ) • ksort($A); .
• print(" [$key] = >$value <br />"); • print "<br/>";
• asort($A); • print "<b>Sorted Array by ksort
• print "<br/>"; function:<b><br/>";
• print "<b>Sorted Array by asort • foreach($A as $key= >$value)
function:<b><br/>"; • print("[$key]=>$value <br />");
• foreach($A as $key= >$value) • ?>
• print("[$key]= >$value <br />");
• Use an array to store student information
such as enrollment no, name, semester and
percentage. Output the data to a web page
using PHP:
• Sol. :<html > • for($i=0;$i <3;$i+ +)
• <head></head> • {
• <body> • echo "<tr>":
• <?php • for($j=0;$j<4;$j++ )
• $a=array(array(l0,"AAA","II",60),ar • {
ray(20,"BBB","III",80),array • echo "<td >";
(30,"CCC","IV",40)); • echo $a[$i][$j];
• echo "<table border =’1’>"; • echo "</td>";
• echo "<tr>"; • }
• echo"<td> ENo, </td><td> Name • echo "</tr>";
</td><td>Sem </td><td> • }
Marks</td>"; • echo "</table>";
• echo "</tr>"; • ?></body></html>

Common questions

Powered by AI

Key PHP functions for array manipulation include array_keys() and array_values() for obtaining keys and values separately, array_key_exists() to check for a key's presence, sort(), asort(), and ksort() for sorting arrays by values or keys, and implode() and explode() for converting between strings and arrays. These functions provide robust tools for comprehensive array processing .

PHP's sort function sorts an array based on its values, resetting and reindexing the keys to numeric indices starting from zero. This changes the original key-value pair associations, which is useful for ordered data retrieval but may not be desirable when key associations are important .

PHP arrays can hold elements of mixed types within a single array, handling integers, strings, and other data types without restriction, unlike traditional typed arrays that enforce a single datatype for all elements. This flexibility allows for more dynamic and versatile data structures, facilitating easier management of heterogeneous data .

The implode function joins array elements into a string, useful for creating CSV-like data or sentences. Explode splits a string into array elements based on delimiters. For instance, implode can concatenate words, while explode can tokenize a sentence into manageable parts .

PHP arrays use an internal pointer to access elements in sequence. The pointer starts at the first element; functions like current(), next(), and each() manipulate it to traverse the array, enabling iteration without manual index tracking, simplifying access patterns .

The sort function orders array elements by values with re-indexed keys, useful for simple list sorting. asort maintains key associations while sorting values, better for maintaining data integrity. ksort orders by keys, maintaining key-value pairs, suitable for predictable key ordering scenarios .

PHP’s arrays can be multidimensional by nesting arrays within arrays, creating matrix-like structures. Practical applications include complex data storage like table data or nested relationships, such as organizational hierarchies, enabling hierarchically structured data manipulation .

To calculate the average, sum all the values using array_sum() then divide by the count using count(). Example: In an associative array $person_age, sum the ages using $sum = array_sum($person_age); then calculate the average as $avg = $sum / count($person_age).

Indexed arrays use numeric indices starting from zero, suitable for ordered collection of data. Associative arrays use named keys, enabling a mapping of key-value pairs which is useful for datasets where the relationship between elements is more important than order, such as dictionaries or mappings .

foreach simplifies syntax by automatically iterating over arrays without needing explicit index control, enhancing readability and reducing errors in accessing elements. However, it lacks fine-grained control over iteration flow available in for loops, potentially limiting complex iteration scenarios .

You might also like