Open In App

How to Declare and Initialize 3×3 Matrix in PHP ?

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

PHP, a widely used scripting language, is primarily known for its web development capabilities. However, it also offers a robust set of features to perform various other programming tasks, including the creation and manipulation of matrices. A matrix is a two-dimensional array consisting of rows and columns, widely used in mathematical computations. This article will guide you through the process of declaring and initializing a 3×3 matrix in PHP, covering all possible approaches.

Approach 1: Using Indexed Arrays

The simplest way to declare and initialize a 3×3 matrix in PHP is by using indexed arrays. Each element of the main array will be another array representing a row in the matrix.

PHP




<?php
  
$matrix = [
    [1, 2, 3], // Row 1
    [4, 5, 6], // Row 2
    [7, 8, 9]  // Row 3
];
  
// Display the matrix
foreach ($matrix as $row) {
    foreach ($row as $value) {
        echo $value . " ";
    }
    echo "\n";
}
  
?>


Output

1 2 3 
4 5 6 
7 8 9 

Approach 2: Using Associative Arrays

For cases where you might need to access elements by a specific key or name, associative arrays can be used. This method is useful when the matrix’s row or column has specific identifiers, making the code more readable and easier to manage.

PHP




<?php
  
$matrix = [
    "row1" => ["col1" => 1, "col2" => 2, "col3" => 3],
    "row2" => ["col1" => 4, "col2" => 5, "col3" => 6],
    "row3" => ["col1" => 7, "col2" => 8, "col3" => 9]
];
  
// Display the matrix
foreach ($matrix as $rowName => $row) {
    echo $rowName . ": ";
    foreach ($row as $colName => $value) {
        echo $colName . "=" . $value . " ";
    }
    echo "\n";
}
  
?>


Output

row1: col1=1 col2=2 col3=3 
row2: col1=4 col2=5 col3=6 
row3: col1=7 col2=8 col3=9 

Approach 3: Dynamically Creating a Matrix

When the values of the matrix are not known beforehand or need to be generated dynamically, you can use loops to initialize the matrix.

PHP




<?php
  
$matrix = [];
$value = 1;
  
for ($i = 0; $i < 3; $i++) {
    for ($j = 0; $j < 3; $j++) {
        $matrix[$i][$j] = $value++;
    }
}
  
// Display the matrix
foreach ($matrix as $row) {
    foreach ($row as $value) {
        echo $value . " ";
    }
    echo "\n";
}
  
?>


Output

1 2 3 
4 5 6 
7 8 9 

Approach 4: Using Array Functions

PHP’s array functions can also be utilized to create matrices. For example, array_fill() can be used to initialize a matrix with the same value.

PHP




<?php
  
// Create a 3x3 matrix filled with zeros
$matrix = array_fill(0, 3, array_fill(0, 3, 0));
  
// Display the matrix
foreach ($matrix as $row) {
    foreach ($row as $value) {
        echo $value . " ";
    }
    echo "\n";
}
  
?>


Output

0 0 0 
0 0 0 
0 0 0 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads