Ngonyoku
Ngonyoku

Reputation: 21

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

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>";
    }

Upvotes: 2

Views: 52

Answers (3)

jspit
jspit

Reputation: 7703

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.

Upvotes: 0

jacouh
jacouh

Reputation: 8741

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>";
  }
?>

Upvotes: 3

Banzay
Banzay

Reputation: 9470

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>";
}

Upvotes: 0

Related Questions