/    Sign up×
Community /Pin to ProfileBookmark

php in_array multi dimensional

Put simply, I’m looping through my database results and making an array of winners. 

The problem is with my in_array function I want to check if the master array as a nested array with the teamID of my winner or not. See below. Any ideas?  

When I check winner against  just $arr it adds a new item to for every winner, so a team may show 10 times 

$arr = array();while ($row = $result->fetch_assoc()) {            
if(in_array($row['Winner'], $arr['teamId'], true)){           

 } else {
    $arr[] = array('teamId' => $row['Winner'], 'Cnt' => 1);           
to post a comment

2 Comments(s)

Copy linkTweet thisAlerts:
@sibertJul 08.2023 — I’m looping through my database results...

I have found that looping through database results often (not always) can be done by a SQL query in one step. I have found that the WITH statement (CTE) is a very good way to move looping from your application code back to the SQL query. Faster and simpler.

I have not seen so many example that are using WITH in SQL queries. But basically there is two queries that works together. Create a LIST in WITH and then use this list to do further steps in the next query.

WITH list AS (SELECT * FROM team) //first query
SELECT sum(wins) FROM (SELECT * FROM list) //second query using the "list"
Copy linkTweet thisAlerts:
@buddyhelpAug 09.2023 — You can achieve this by using a flag to check whether a team ID exists in the $arr array. Here's the modified code snippet:

$arr = array();

while ($row = $result->fetch_assoc()) {
$found = false;

foreach ($arr as &$item) {
if ($item['teamId'] === $row['Winner']) {
$found = true;

if (!$found) {
$arr[] = array('teamId' => $row['Winner'], 'Cnt' => 1);

In this code, we iterate through the $arr array to check if the teamId already exists. If it does, we increment the Cnt value. If not, we add a new item to the array. This way, the team ID will not be added multiple times for the same winner. Let me know if you have questions. Thanks


Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 11.28,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ

legal: ({
terms: of use,
privacy: policy
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
recent_tips: (
tipper: @bahaedd,
tipped: article
amount: 1000 SATS,

tipper: @Balmasexy,
tipped: article
amount: 1000 SATS,

tipper: @mbsaad,
tipped: article
amount: 1000 SATS,