w3resource

PHP Array Exercises : Print two values from a given array


19. Print Specific Elements from Multidimensional Array

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

For more Practice: Solve these Related Problems:

  • Write a PHP script to extract and print the value associated with key "b" from a nested array and then display a specific element from another sub-array.
  • Write a PHP function that navigates a multidimensional array to retrieve specific elements given their keys.
  • Write a PHP program to merge two sub-arrays from a multidimensional array and output the desired elements with a formatted message.
  • Write a PHP script to combine elements from a multidimensional array based on provided keys and display them in a sentence.

Go to:


PREV : Floor Decimal with Precision.
NEXT : Sort Array by Priority List.

PHP Code Editor:



Contribute your code and comments through Disqus.

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.