DEV Community

Cover image for Set theory(with PHP)
Luis "shadowtampa" Gomes
Luis "shadowtampa" Gomes

Posted on

Set theory(with PHP)

Heres a Cheat Sheet I made for joins! Also, here are some PHP 8 examples with sets. Its important to master the basics, because in the future youll spend less time trying to build workarounds for simple solutions.

Image description

`<?php

$array_a = [1,2,3,4,5];
$array_b = [2,3,4,5,6];

function left_excluding_join($left, $right) {
return array_diff($left, $right);
}

function left_outer_join($left, $right) {
return $left;
}

function right_excluding_join($left, $right) {
return array_diff($right, $left);
}

function right_outer_join($left, $right) {
return $right;
}

function full_join($left, $right) {
return array_unique(array_merge($left, $right));
}

function inner_join($left, $right) {
return array_intersect($left, $right);
}

function outer_excluding_join($left, $right) {
return array_diff(full_join($left, $right), inner_join($left, $right));
}

echo "=== LEFT EXCLUDING JOIN ===\n";
print_r (left_excluding_join($array_a, $array_b));

echo "=== LEFT OUTER JOIN ===\n";
print_r (left_outer_join($array_a, $array_b));

echo "=== RIGHT EXCLUDING JOIN ===\n";
print_r (right_excluding_join($array_a, $array_b));

echo "=== RIGHT OUTER JOIN ===\n";
print_r (RIGHT_outer_join($array_a, $array_b));

echo "=== FULL JOIN ===\n";
print_r (full_join($array_a, $array_b));

echo "=== INNER JOIN ===\n";
print_r (inner_join($array_a, $array_b));

echo "=== OUTER EXCLUDING JOIN ===\n";
print_r (outer_excluding_join($array_a, $array_b));
`

And the results:

=== LEFT EXCLUDING JOIN ===
Array
(
[0] => 1
)
=== LEFT OUTER JOIN ===
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
=== RIGHT EXCLUDING JOIN ===
Array
(
[4] => 6
)
=== RIGHT OUTER JOIN ===
Array
(
[0] => 2
[1] => 3
[2] => 4
[3] => 5
[4] => 6
)
=== FULL JOIN ===
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[9] => 6
)
=== INNER JOIN ===
Array
(
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
=== OUTER EXCLUDING JOIN ===
Array
(
[0] => 1
[9] => 6
)

Top comments (2)

Collapse
 
maksimepikhin profile image
Maksim N Epikhin (PIKHTA) • Edited

The left_outer_join and right_outer_join methods don't make sense. What about associative and nested arrays?

Collapse
 
vilailus profile image
Luis "shadowtampa" Gomes

I thought I could just retrieve the array in those two methods since that would be an direct approach. Indeed, I have not posted about those other two possibilities... an opportunity for me! Thank you.