Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php array count in with dynamic result

Tags:

arrays

php

i am trying to count a result of a array i get back from a script. there are two cases that i can get back option a is

Array ( [Id] => 1779 [SupplierId] => 1809 [SupplierName] => cccccc)

And second option ib

Array ( 
[0] => Array ( [Id] => 2020 [SupplierId] => 1809 [SupplierName] => vvv) 
[1] => Array ( [Id] => 2058 [SupplierId] => 1809 [SupplierName] => bbb) 
[2] => Array ( [Id] => 2063 [SupplierId] => 1809 [SupplierName] => xx) 
)

if i do count in to cases i get back 3 How can i count that in option A i get back 1, and in option B i will get back 3 ?

like image 915
Dani Evan Rubenstein Avatar asked Mar 07 '26 13:03

Dani Evan Rubenstein


1 Answers

You can create a function like this:

function countRes($arr) {
    return is_array(end($arr)) ? count($arr) : 1;
}

$arr1 = array("Id" => 1779, "SupplierId" => 1809, "SupplierName" => "cccccc");

$arr2 = array(array("Id" => 2020, "SupplierId" => 1809, "SupplierName" => "vvv"),
              array("Id" => 2058, "SupplierId" => 1809, "SupplierName" => "bbb"),
              array("Id" => 2063, "SupplierId" => 1809, "SupplierName" => "xx"));

echo countRes($arr1); // 1
echo countRes($arr2); // 3

It checks if the last element is an array, and returns the number of arrays in the resulting array. Otherwise it returns 1 because the resulting array itself contains the data.

like image 87
Rax Weber Avatar answered Mar 09 '26 02:03

Rax Weber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!