Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP Array Examples
<?php
// Sample Arrays
$arrBooks = array(
"Comic" => array(
"Title" => "Superman",
"Author" => "Jerry Siegel",
"Publication Date" => "1938"),
"Science Fiction" => array(
"Title" => "Dune",
"Author" => "Frank Herbert",
"Publication Date" => "1965"),
"Fantasy" => array(
"Title" => "The Hobbit",
"Author" => "J.R.R. Tolkien",
"Publication Date" => "1937"),
"Horror" => array(
"Title" => "Carrie",
"Author" => "Stephen King",
"Publication Date" => "1974"),
);
$arrBooks2 = array(
"Comic" => "Superman",
"ScienceFiction" => "Dune",
"Fantasy" => "The Hobbit",
"Horror" => "Carrie"
);
// Extracting elements from multidimentional array
echo $arrBooks['Science Fiction']['Title'];
echo "<br>";
echo $arrBooks['Horror']['Author'];
// Looping
echo "<pre>";
print_r($arrBooks);
foreach($arrBooks as $obj_key => $book) {
echo $obj_key."Book:<br>";
foreach($book as $key=>$value){
echo $key." : ".$value."<br>";
}
echo "<br>";
}
/*** Array functions ***/
// Count function
$numBooks = count($arrBooks);
echo "There are ".$numBooks." books in the collection.<br>";
// Extract function
extract($arrBooks2);
$arrBooks2[‘Comic’] becomes $Comic
$arrBooks2[‘ScienceFiction’] becomes $ScienceFiction
$arrBooks2[‘Fantasy] becomes $Fantasy
$arrBooks2[‘Horror] becomes $Horror
echo "$Comic is a comic book.<br>";
echo "$Fantasy is a fantasy book.<br>";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment