Fero
Fero

Reputation: 13315

How can i count the two-dimesional array - PHP

Array
(
    [0] => Array
    (
        [not_valid_user] => Array
        (
            [] => asdsad
        )
    )
    [1] => Array
    (
    )
    [2] => Array
    (
        [not_valid_user] => Array
        (
            [] =>  asdasd
        )
    )
)

I need the count of array [not_valid_user]

For example:

The above arrays count is 2. How can i get it?

Thanks in advance...

Upvotes: 0

Views: 130

Answers (4)

Manjula
Manjula

Reputation: 5101

If what you want is count of all elements in every "not_valid_user" array,

$count=0;
foreach($mainArray as $innerArray)
{

 if (isset($innerArray['not_valid_user']) && is_array($innerArray['not_valid_user']))
 { 
    $count += count($innerArray['not_valid_user']);// get the size of the 'not_valid_user' array
 } 
}

echo $count;//Count of all elements of  not_valid_user

Upvotes: 2

Dormouse
Dormouse

Reputation: 5198

$cnt = 0;

array_map(function ($value) use (&$cnt) {

    $cnt += (int)(isset($value["not_a_valid_user"]));

}, $arr);

echo $cnt;

Providing your version of PHP supports anonymous functions.

Upvotes: 0

Akhil Thayyil
Akhil Thayyil

Reputation: 9413

<?php
$count=0;
foreach($mainArray as $innerArray)
{

if(isset($innerArray['not_valid_user']))
  $count++;
}

echo $count;//Count of not_valid_user

?>

Upvotes: 0

Jan Hančič
Jan Hančič

Reputation: 53929

$invalidUsersFound = 0;
foreach ( $data as $k => $v ) {
  if ( IsSet ( $v['not_valid_user'] ) === true )
    $invalidUsersFound++;
}

This should do the trick.

Upvotes: 2

Related Questions