Jump to content

Recommended Posts

1 minute ago, taquitosensei said:

I just tried the syntax and it works. Have you tried it? Without knowing where $ARR and $NEEDLE come from and what they look like. It's hard to know what the problem is.

$ARR  is any array and $NEEDLE is a value you are trying to count occurances of.

Tho overall code works, the original version was

if($ARR[$i] == $NEEDLE){
	$Count++;
	}

but I thought the newer version cleaner

Edited by Karaethon

oops, not that it makes much of a difference but i mis-typed when i wrote it here it's

function countIf( $ARR, $NEEDLE){
  $Count = 0;         
  foreach( $ARR as $Entry){             
    $Entry === $NEEDLE ? $Count++ : $Count;
  }
  return $Count;
 }
Edited by Karaethon
2 minutes ago, NotionCommotion said:

Actually, I first thought it was valid but when first tried, it didn't work because of a typo.

http://sandbox.onlinephpfunctions.com/code/71d97ebba750645b61dbfe821a9cf76e836ffec2

I followed your link (neat site, gonna bookmark it) and it did work when i tried it...

12 minutes ago, Barand said:

try


function countIf($arr, $needle) 
{
    $counts = array_count_values($arr);
    return $counts[$needle] ?? 0;
}

 

CARP! I wrote countIf because all my searching of php documentation I couldnt find anything that let me search specific value.... I must have missed array_count_values, because it doesnt look for specific I moved on. I remember seeing it. arghhhh!

all i needed was

array_count_values(ARRAY)[VALUE IM LOKING FOR]

ONE FREAKIN LINE!!!!

Edited by Karaethon
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.