1

I am using laravel 5, I need count the keys available inside every array index suppose for array[0] it has 7 keys, now I need the last key and before last key to compare which's value is bigger. how I can do using loop,as far I have tried.

Please Note The inner keys are stored as object key=>value pair.

foreach ($regions as $regions_key => $regions_value) {
        echo sizeof($regions_key)
    }

enter image description here

Help is appreciated.

9
  • Should be this: count(array_keys($arr)) Commented May 31, 2016 at 5:33
  • The following url not solving the problem which I am facing in.. Commented May 31, 2016 at 5:34
  • Also check stackoverflow.com/questions/8284302/… Commented May 31, 2016 at 5:39
  • all your sub array size is same so you can do $total_keys = count(array_keys($arr)) * count(array_keys($arr[0])) Commented May 31, 2016 at 5:44
  • @Saty your last help is for 2D array but I am struggling in objects value count.. Commented May 31, 2016 at 6:04

3 Answers 3

1

Wouldn't you just count it within your loop:

$total = 0;
foreach($data as $sub_array) {
    $total += count($sub_array);
}

After the above iteration is done to find your counts, $total will hold your count.

Example/Demo

Sign up to request clarification or add additional context in comments.

10 Comments

If it is mark as Duplicate than why answers??
@FrayneKonok Look at the duplicate - that's only for a 1 dimensional array, this question is 2D
it gives me outer array key,I need inside one of each.
I have supposed to get here to get help,if someone is not willing to help me then why this stackoverflow for while the question is not duplicate indeed,I have posted here after searching a long.
@FrayneKonok that isn't a bad idea ;-) but you dunno if OP's array's all have the same amount as the first !
|
0

Try this:

$countArr = array();
foreach ($regions as $regions_key => $regions_value) {
   $countArr[$regions_key] = count($regions[$regions_key]); // create array of length of sub array
}
echo max($countArr); // max — Find highest value

7 Comments

If it is mark as Duplicate than why answers??
where duplication marked??
What is the first comment in the question???
if marked as duplicated why you answered below that comment??? :)
You can check the time between those comments.....
|
0

To count the number of keys in an array. Try

$arr = Array
    (
        0 => 'hello',
        1 => 'there',
        2 => null,
        3 => null,
        4 => 3,
    );
var_dump(count($arr)); 

1 Comment

Thanks to every one. At last worked for me $iCount = 0; foreach ($regions as $regions_key => $regions_value) { foreach ($regions_value as $key => $value) { $iCount = count((array)$regions_value); } } echo $iCount;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.