A set is a simply a collection of values without any particular order. It can contain any data type and we can run different set operations such as union, intersection, complement, and so on. As a set only contains values, we can construct a basic PHP array and assign values to it so that it grows dynamically. The following example shows two sets that we have defined; one contains some odd numbers and the other one has some prime numbers:
$odd = [];
$odd[] = 1;
$odd[] = 3;
$odd[] = 5;
$odd[] = 7;
$odd[] = 9;
$prime = [];
$prime[] = 2;
$prime[] = 3;
$prime[] = 5;
In order to check the existence of a value inside the set along with union, intersection, and complement operation, we can use the following example:
if (in_array(2, $prime)) {
echo "2 is a prime";
}
$union = array_merge($prime, $odd);
$intersection = array_intersect($prime, $odd);
$compliment = array_diff($prime, $odd);
PHP has many built-in functions for such operations and we can utilize them for our set operations. But we have to consider one fact: since the set is not ordered in any particular way, searching using the in_array() function might have the complexity of O(n) in worst case scenario. Same goes for the array_merge() function, as it will check each value from one array with another array. In order to speed things up, we can modify our code a little bit and make it efficient:
$odd = [];
$odd[1] = true;
$odd[3] = true;
$odd[5] = true;
$odd[7] = true;
$odd[9] = true;
$prime = [];
$prime[2] = true;
$prime[3] = true;
$prime[5] = true;
if (isset($prime[2])) {
echo "2 is a prime";
}
$union = $prime + $odd;
$intersection = array_intersect_key($prime, $odd);
$compliment = array_diff_key($prime, $odd);
If we analyze this code, we can see that we are using an index or key to define the set. Since a PHP array index or key lookup have a complexity of O(1), it makes the searching much faster. As a result, all the lookup, union, intersect, and complement operations will take lesser time compared to the previous example.