PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, January 11, 2022

[FIXED] Counts occurrences in multidimensional array

 January 11, 2022     php     No comments   

Issue

The contents of this question have been removed due to a DMCA Takedown request by TestDome d.o.o.


Solution

This happens because your array $arr contains a string (apple) and arrays:

$arr = [
  "apple",
  ["banana", "strawberry", "apple"],
  ["banana", "strawberry", "apple", ["banana", "strawberry", "apple"]]
];

$count = 0;

foreach ($arr as $arritem) {
    // first iteration: $arritem is "apple"
    // second iteration: $arritem is ["banana", ...]
    // third iteration: $arritem is ["banana", ...]
    if ($arritem === "apple") {
        $count++;
    }
}

echo $count;

$arritem === "apple" only holds true for one element in the array, hence the output 1.

How to fix ? Use array_walk_recursive to recursively walk the array(s):

$count = 0;

array_walk_recursive($arr, function($item) use (&$count) {
    if ($item === "apple") ++$count;
});

echo $count; // outputs 4


Answered By - marco-a
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing