0

I have array with stdClasses:

$a = new \stdClass();
$a->name = "aaa";
$a->type = "1";

$b = new \stdClass();
$b->name = "bbb";
$b->type = "2";

$c = new \stdClass();
$c->name = "ccc";
$c->type = "1";

$array = array($a, $b, $c);

$count = 0;

foreach ($array as $arr) {
    if ($arr->type == 1) {
        $count++;
    }
}

Is better way to count types with value 1 than foreach? I would like counting many values so foreach is uncomfortable.

Maybe array_search or array_map?

Sneh Pandya
  • 8,197
  • 7
  • 35
  • 50
levo
  • 3
  • 2
  • what you are using is best in your requirement already – AZinkey Oct 12 '17 at 06:45
  • you should read it also https://stackoverflow.com/questions/18144782/performance-of-foreach-array-map-with-lambda-and-array-map-with-static-function/26527704#26527704 – AZinkey Oct 12 '17 at 06:56
  • Have you checked that foreach is actually slow? This sounds a lot like premature optimization. At some place in your code there will be a full iteration of the data, moving that bit, would just hide the fact not prevent it. – Yoshi Oct 12 '17 at 06:56

1 Answers1

3

You can use array_filter:

http://php.net/manual/tr/function.array-filter.php

example:

$a = new \stdClass();
$a->name = "aaa";
$a->type = "1";

$b = new \stdClass();
$b->name = "bbb";
$b->type = "2";

$c = new \stdClass();
$c->name = "ccc";
$c->type = "1";

$array = array($a, $b, $c);

$count = count(array_filter($array, function($d){
     return $d->type === "1";
}));
Taha Paksu
  • 15,371
  • 2
  • 44
  • 78
  • Have you checked that this is any faster than simple foreach? – Yoshi Oct 12 '17 at 06:54
  • Yep, it seems that there isn't so much difference between those. I was reading this when you've asked the above question: https://laracasts.com/discuss/channels/code-review/why-array-maparray-filter-over-foreach – Taha Paksu Oct 12 '17 at 06:56
  • And here I found some benchmarks: http://www.levijackson.net/are-array_-functions-faster-than-loops/ – Taha Paksu Oct 12 '17 at 06:58