w3resource

PHP Array Exercises : Print two values from a given array

PHP Array: Exercise-19 with Solution

Write a PHP script to print "second" and Red from the following array.
Sample Data :
$color = array ( "color" => array ( "a" => "Red", "b" => "Green", "c" => "White"),
"numbers" => array ( 1, 2, 3, 4, 5, 6 ),
"holes" => array ( "First", 5 => "Second", "Third"));

Sample Solution:

PHP Code:

<?php
// Define a multi-dimensional associative array named $color
$color = array(
    "color" => array("a" => "Red", "b" => "Green", "c" => "White"),
    "numbers" => array(1, 2, 3, 4, 5, 6),
    "holes" => array("First", 5 => "Second", "Third")
);

// Print the value associated with the key 5 in the "holes" sub-array
echo $color["holes"][5] . "\n"; // prints "Second"

// Print the value associated with the key "a" in the "color" sub-array
echo $color["color"]["a"] . "\n"; // prints "Red"
?>

Output:

Second                                                      
Red    

Flowchart:

Flowchart: Print two values from a given array

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP function to floor decimal numbers with precision.
Next: Write a PHP function to sort an array according to another array acting as a priority list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.