phparraysmultidimensional-arrayfilteringcounting

Count occasions when a column value in a 2d array starts with a specified letter


I want to know if there is another solution to what I'm doing here:

$array = [
    ['Name' => 'Apple', 'Count' => 10]
    ['Name' => 'Tomato', 'Count' => 23],
    ['Name' => 'Tree', 'Count' => 4],
    ['Name' => 'Potato', 'Count' => 44],
    ['Name' => 'Apple', 'Count' => 73],
];

//Generate string with the 'Name's'
$aNamesMain = [];
$nCounterMain = 0;
$aNamesMain = array_merge($aNamenMais, array_keys($array['Name']));

foreach ($aNamesMain as $name) {
    // Check to see which items start with an A
    if (substr('$name', 0, 1) === 'A') { $nCounterMain++; }
}

So I want to know how many times an item is found in my array at the 'Name' => place that starts with a specific letter. A in this case. But as I got it to work now it's like I posted above, but isn't there a better way to achieve this?

Some array function or something, because I've been trying some from the PHP manual but can't seem to find a better solution right now.

Something so I won't have to use the foreach or get rid of the array merge.


Solution

  • You can use array_filter with a anonymous function to solve this:

    //your array containing the items.
    $aArray = array(
        array('Name' => 'Apple', 'Count' => 10),
        array('Name' => 'Tomato', 'Count' => 23),
        array('Name' => 'Tree', 'Count' => 4),
        array('Name' => 'Potato', 'Count' => 44),
        array('Name' => 'Apple', 'Count' => 73)
    );
    
    //the character or string you want to search.   
    $startWithChar = 'A';
    
    //get all items of the array starting with the specified character or string.  
    $newArray = array_filter($aArray, function($v) use ($startWithChar) {
        return strpos($v['Name'], $startWithChar) === 0;
    });
    
    echo count($newArray); //2
    

    demo: https://ideone.com/EctCs7