/    Sign up×
Community /Pin to ProfileBookmark

Match All Array Items as Pairs

This is a weird one, I’ve got a scenario where an array of items are being posted via a form. The array are ID’s.

I need to pair each ID with the other. For example; if I have 1,2,3,4,5 I need
1 – 2
1 – 3
1 – 4
1 – 5
2 – 3
2 – 4
2 – 5

I do not want to duplicate them either, what’s the best way to do this?

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@NogDogDec 03.2022 — There may be some more clever/efficient way to do this, but this seems to work:
[code=php]
$ids = [3, 1, 5, 4, 2];
sort($ids);
$ids_copy = $ids;
$result = [];
foreach($ids as $id) {
foreach($ids_copy as $id2) {
if($id2 > $id) {
$result[] = [$id, $id2];
}
}
}
print_r($result);
[/code]

outputs:
[code=text]
Array
(
[0] => Array
(
[0] => 1
[1] => 2
)
[1] => Array
(
[0] => 1
[1] => 3
)
[2] => Array
(
[0] => 1
[1] => 4
)
[3] => Array
(
[0] => 1
[1] => 5
)
[4] => Array
(
[0] => 2
[1] => 3
)
[5] => Array
(
[0] => 2
[1] => 4
)
[6] => Array
(
[0] => 2
[1] => 5
)
[7] => Array
(
[0] => 3
[1] => 4
)
[8] => Array
(
[0] => 3
[1] => 5
)
[9] => Array
(
[0] => 4
[1] => 5
)
)
[/code]
×

Success!

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 5.18,
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: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

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

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...