How do i find the number of elemets in a 2 demensional array in PHP?

Viewed 47

Is there a function which can be used to get the number of columns of a 2D array? I've come to realize that count() function will display the number of rows inside the 2D array but am interested in getting the number of columns inside each array.
How can I use the count() function or any other function to get the number of elements inside an array contained inside another array. Here is a sample of the code that am working with:

<?php
    $people = array(
            array("Rodrick","Java","PHP"),
            array("Jane","Python","Javascript"),
            array("Tom","Python","R"),
            array("Wangari","Ruby","Kotlin"),
    );

    for($row = 0 ; $row < count($people) ; $row++){
        echo "The Programmers ".$row;
        echo "<ol>";
        for($col = 0 ; $col < 3 ;$col++){
            echo "<li>".$people[$row][$col]."</li>";
        }
        echo "</ol>";
    }
3 Answers

You can get the size of the second dimension by:

$ncols = count($people[$row]);

Your code could be like this:

<?php
  $people = array(
        array("Rodrick","Java","PHP"),
        array("Jane","Python","Javascript"),
        array("Tom","Python","R"),
        array("Wangari","Ruby","Kotlin"),
  );

  for($row = 0 ; $row < count($people) ; $row++){
    echo "The Programmers ".$row;
    echo "<ol>";
    $ncols = count($people[$row]);
    for($col = 0 ; $col < $ncols ; $col++){
        echo "<li>".$people[$row][$col]."</li>";
    }
    echo "</ol>";
  }
?>

Do you really need to know the size of nested array?

Here is solution with foreach used:

$people = array(
        array("Rodrick","Java","PHP"),
        array("Jane","Python","Javascript"),
        array("Tom","Python","R"),
        array("Wangari","Ruby","Kotlin"),
);

foreach($people as $human){
    echo "<ol>";
    foreach($human as $data){
        echo "<li>".$data."</li>";
    }
    echo "</ol>";
}

The number of columns is determined here on the basis of the first line.

$numberOfColumns = count(reset($people));

The calculation can be used for numerical and also for associative arrays.

Related