w3resource
php Programming Exercies

PHP Array Exercises : Create a two-dimensional array

PHP Array: Exercise-56 with Solution

Write a PHP script to create a two-dimensional array (4x4), initialized to 10.

Note: Use array_fill() function.

Sample Solution:

PHP Code:

<?php
$a = array_fill(0, 4, array_fill(0, 4, 10));
  print_r($a);
?>

Sample Output:

Array                                                       
(                                                           
    [0] => Array                                            
        (                                                   
            [0] => 10                                       
            [1] => 10                                       
            [2] => 10                                       
            [3] => 10                                       
        )                                                   
                                                            
    [1] => Array                                            
        (                                                   
            [0] => 10                                       
            [1] => 10                                       
            [2] => 10                                       
            [3] => 10                                       
        )                                                   
                                                            
    [2] => Array                                            
        (                                                   
            [0] => 10                                       
            [1] => 10                                       
            [2] => 10                                       
            [3] => 10                                       
        )                                                   
                                                            
    [3] => Array                                            
        (                                                   
            [0] => 10                                       
            [1] => 10                                       
            [2] => 10                                       
            [3] => 10                                       
        )                                                   
                                                            
)

Flowchart:

Flowchart: PHP - Create a two dimensional array

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP function to convert a string to an array (trimming every line and remove empty lines).
Next: Write a PHP function to compares two multidimensional arrays and returns the difference.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming