Jump to content
Karaethon

Is this valid syntax?

Recommended Posts

Posted (edited)
$ARR[$i] == $NEEDLE ? $Count++ : $Count

I am using it in:

private function _countIf($ARR, $NEEDLE){ 
  $Count = 0;
  for($i = 0; $i < count($ARR); i++){
    $ARR[$i] == $NEEDLE ? $Count++ : $Count
  }
  return $Count;
}
Edited by Karaethon

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

Havent yet tried it, its one method in a class im writing and it's callers are still under comstruction.

Share this post


Link to post
Share on other sites
Posted (edited)
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

Share this post


Link to post
Share on other sites
Posted (edited)

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

Share this post


Link to post
Share on other sites

try

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

 

Share this post


Link to post
Share on other sites
Posted (edited)
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

Share this post


Link to post
Share on other sites

Alternatively

function countIf($arr, $needle) 
{
   return count(array_keys($arr, $needle));
}

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×

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.