F
F
felony13twelve2020-05-23 10:30:45
PHP
felony13twelve, 2020-05-23 10:30:45

How to get the number of values ​​since 1 in an array?

Good morning everyone! Probably for you it will seem a more stupid question, but I don’t remember, because I didn’t even know how. In general, back to the topic!
There is such an array How to get the number of values ​​with "1"? I tried several codes, which my small, stupid brain was enough for :D, but unfortunately it doesn’t work, sometimes it displays an error, sometimes it displays something else. In general, rubbish :) If someone is interested in how I tried it, then I'll throw off the code, but this is if you need it :)
$arr = array(1, 46, 2, 1, 1, 737);

Answer the question

In order to leave comments, you need to log in

4 answer(s)
O
OxCom, 2020-05-23
@felony13twelve

maybe not optimal, but

$arr = array(1, 46, 2, 1, 1, 737);
var_dump(\count(\array_filter($arr, function($v) {return $v === 1;})));

or in a loop to calculate:
<?php
$arr = array(1, 46, 2, 1, 1, 737);
$cnt = 0;
foreach ($arr as $v) {
    $cnt += $v === 1 ? 1 : 0;
}
var_dump($cnt);

I
Ilya, 2020-05-23
@New_Horizons

$countOne = array_count_values($arr)[1] ?? 0;

F
FanatPHP, 2020-05-23
@FanatPHP

Drop this thing. Seriously.
This is not a ride. This is a diagnosis.
You've been munching on programming for at least a year now, and this is not your first acc on the toaster.
And at the same time, they are not able to algorithmize the simplest operation, just an elementary one, a loop + a conditional transition. Easier already nowhere.
programming is clearly not for you. No need to torture yourself and others. Find a job that suits your abilities best.

E
Eugene, 2020-05-23
@Kasperenysh

read here

$arr = array(1, 46, 2, 1, 1, 737);

function sum($carry, $item)
{
    if($item == 1) $carry += 1;
    return $carry;
}

var_dump(array_reduce($arr, "sum"));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question