0% found this document useful (0 votes)
10 views1 page

PHP Arrays: Indexed & Associative Guide

The document provides a PHP script demonstrating the creation and manipulation of indexed and associative arrays. It includes examples of adding elements, iterating through arrays, sorting, and counting elements. The script outputs the contents and details of the arrays to the console.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views1 page

PHP Arrays: Indexed & Associative Guide

The document provides a PHP script demonstrating the creation and manipulation of indexed and associative arrays. It includes examples of adding elements, iterating through arrays, sorting, and counting elements. The script outputs the contents and details of the arrays to the console.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

<?

php
// 1. Creating an Indexed Array
$fruits = array("Apple", "Banana", "Cherry");

// 2. Adding an Element to the Array


$fruits[] = "Date"; // Adds "Date" to the end of the array

// 3. Creating an Associative Array


$person = array(
"first_name" => "John",
"last_name" => "Doe",
"age" => 30
);

// 4. Adding an Element to the Associative Array


$person["email"] = "[Link]@[Link]";

// 5. Iterating Through the Indexed Array


echo "Fruits in the array:\n";
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}

// 6. Iterating Through the Associative Array


echo "\nPerson Details:\n";
foreach ($person as $key => $value) {
echo ucfirst($key) . ": " . $value . "\n";
}

// 7. Array Functions: Sorting the Indexed Array


sort($fruits);
echo "\nSorted Fruits:\n";
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}

// 8. Array Functions: Getting the Number of Elements in an Array


$numberOfFruits = count($fruits);
echo "\nNumber of fruits in the array: " . $numberOfFruits . "\n";
?>

You might also like