Nothing Special   »   [go: up one dir, main page]

PHP 5 Arrays

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

w3schools.

com
THE WORLD'S LARGEST WEB DEVELOPER SITE

PHP 5 Arrays
Previous

NextChapter

Anarraystoresmultiplevaluesinonesinglevariable:

Example

<?php
$cars=array("Volvo","BMW","Toyota");
echo"Ilike".$cars[0].",".$cars[1]."and".$cars[2].
".";
?>

PHP

Runexample

What is an Array?
Anarrayisaspecialvariable,whichcanholdmorethanonevalueatatime.
Ifyouhavealistofitems(alistofcarnames,forexample),storingthecarsinsingle
variablescouldlooklikethis:

$cars1="Volvo";
$cars2="BMW";
$cars3="Toyota";
However,whatifyouwanttoloopthroughthecarsandfindaspecificone?Andwhat
ifyouhadnot3cars,but300?

Thesolutionistocreateanarray!
Anarraycanholdmanyvaluesunderasinglename,andyoucanaccessthevalues
byreferringtoanindexnumber.

Create an Array in PHP


InPHP,thearray()functionisusedtocreateanarray:

array();
InPHP,therearethreetypesofarrays:
IndexedarraysArrayswithanumericindex
AssociativearraysArrayswithnamedkeys
MultidimensionalarraysArrayscontainingoneormorearrays

PHP Indexed Arrays


Therearetwowaystocreateindexedarrays:
Theindexcanbeassignedautomatically(indexalwaysstartsat0),likethis:

$cars=array("Volvo","BMW","Toyota");
ortheindexcanbeassignedmanually:

$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";
Thefollowingexamplecreatesanindexedarraynamed$cars,assignsthreeelements
toit,andthenprintsatextcontainingthearrayvalues:

Example
<?php
$cars=array("Volvo","BMW","Toyota");
echo"Ilike".$cars[0].",".$cars[1]."and".$cars[2].

".";
?>
Runexample

Get The Length of an Array The count


Function
Thecount()functionisusedtoreturnthelength(thenumberofelements)ofan
array:

Example
<?php
$cars=array("Volvo","BMW","Toyota");
echocount($cars);
?>
Runexample

Loop Through an Indexed Array


Toloopthroughandprintallthevaluesofanindexedarray,youcoulduseaforloop,
likethis:

Example
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++){
echo$cars[$x];
echo"<br>";

}
?>
Runexample

PHP Associative Arrays


Associativearraysarearraysthatusenamedkeysthatyouassigntothem.
Therearetwowaystocreateanassociativearray:

$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
or:

$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";
Thenamedkeyscanthenbeusedinascript:

Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo"Peteris".$age['Peter']."yearsold.";
?>
Runexample

Loop Through an Associative Array


Toloopthroughandprintallthevaluesofanassociativearray,youcouldusea
foreachloop,likethis:

Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($ageas$x=>$x_value){
echo"Key=".$x.",Value=".$x_value;
echo"<br>";
}
?>
Runexample

Multidimensional Arrays
MultidimensionalarrayswillbeexplainedinthePHPadvancedsection.

Complete PHP Array Reference


Foracompletereferenceofallarrayfunctions,gotoourcompletePHPArray
Reference.
Thereferencecontainsabriefdescription,andexamplesofuse,foreachfunction!

Previous

NextChapter

W3SCHOOLS EXAMS
HTML,CSS,JavaScript,PHP,jQuery,BootstrapandXMLCertifications

COLOR PICKER

LEARN MORE:
ColorConverter
GoogleMaps
AnimatedButtons
ModalBoxes
ModalImages
Tooltips
Loaders
JSAnimations
ProgressBars
Dropdowns
Slideshow
SideNavigation
HTMLIncludes
ColorPalettes

SHARE THIS PAGE

REPORTERROR
PRINTPAGE
FORUM
ABOUT

Top 10 Tutorials
HTMLTutorial
CSSTutorial
JavaScriptTutorial
W3.CSSTutorial
BootstrapTutorial

SQLTutorial
PHPTutorial
jQueryTutorial
AngularTutorial
XMLTutorial

Top 10 References
HTMLReference
CSSReference
JavaScriptReference
W3.CSSReference
BrowserStatistics
PHPReference
HTMLColors
HTMLCharacterSets
jQueryReference
AngularJSReference

Top 10 Examples
HTMLExamples
CSSExamples
JavaScriptExamples
W3.CSSExamples
HTMLDOMExamples
PHPExamples
jQueryExamples
ASPExamples
XMLExamples
SVGExamples

Web Certificates
HTMLCertificate
HTML5Certificate
CSSCertificate
JavaScriptCertificate
jQueryCertificate
PHPCertificate
BootstrapCertificate
XMLCertificate

W3Schoolsisoptimizedforlearning,testing,andtraining.Examplesmightbesimplifiedtoimprovereading
andbasicunderstanding.Tutorials,references,andexamplesareconstantlyreviewedtoavoiderrors,but
wecannotwarrantfullcorrectnessofallcontent.Whileusingthissite,youagreetohavereadand
acceptedourtermsofuse,cookieandprivacypolicy.Copyright19992016byRefsnesData.AllRights
Reserved.
PoweredbyW3.CSS.

You might also like