Functions for working with arrays. Set Theory - PHP: Arrays - Hexlet Php intersection of arrays by value
Set theory. I know how many people are afraid of mathematicians, but specifically set theory (naive) is very simple and understandable. Moreover, we constantly use its elements in everyday life. And in programming it occurs at every step.
The basic concept of set theory, surprisingly, is a bunch of. A set denotes a collection of objects of arbitrary nature, considered as a single whole. The simplest example is numbers. The set of Arabic numerals includes 10 elements and is final. The concept of finiteness is intuitive and means that a set has a finite number of elements.
An example of an infinite set is natural numbers. In turn, the set of natural numbers is a subset of integers, which in turn are a subset of rational numbers, and so on.
"Subset" means that all the elements of one set are also included in another set, called superset(relative to a subset).
Representing sets by circles is quite convenient. You can quickly assess how different sets relate to each other.
But mathematical objects such as numbers are not the only possible objects of sets. A set can be called a group of people standing at a bus stop waiting for their bus, or residents of apartments in one house, city or country. Any collection of any objects that we want to consider as a single whole.
The main thing for us in set theory is operations on them. These include: addition, union, intersection, difference, Cartesian product and some others.
A simple example. When you visit another person's page on Facebook, Facebook shows you a block with mutual friends. If we assume that your friends and your friend's friends are two sets, then mutual friends are the set obtained as the intersection of the original sets of friends.
Moving on to programming, you will notice that an array is very similar to a set, and it can indeed be thought of as such. Why is this so important? By understanding the principles behind certain operations, you can implement them in the fastest and most efficient way. For example, knowing that you need a set intersection operation in php, you can try to find a function that does the task. To do this, just enter the query into Google: php set intersect(set - set, intersect - intersection). The first (at least for me) link in the search results leads to the desired array_intersect function. The same thing awaits you with other operations. This is a partial answer to the question “do programmers need mathematics?”
By the way, not all languages have built-in functions for working with sets. In some, you need to install additional libraries for this, and in some, for example, in Ruby, operations with sets are implemented using arithmetic operators (union of sets: coll1 + coll2).
Separately, it is worth saying that relational databases are built on the ideas of relational algebra, in which set theory plays a central role. Databases are an integral part of web development, and we'll get to know them later.
Let's look at the basic operations:
Intersection
The intersection of sets is a set that includes elements that appear in all given sets at the same time.
["vasya", "petya"]
This function accepts any number of arrays. That is, you can find the intersection of any number of arrays in one call.
An association
A union of sets is a set that contains elements of all given sets. Set union in PHP cannot be done with one call, but it can be simulated by connecting two functions:
["vasya", "kolya", "petya", "igor", "petya", "sergey", "vasya", "sasha"]; // unique removes duplicates $sharedFriends = array_unique($friends); // => ["vasya", "kolya", "petya", "igor", "sergey", "sasha"]
Addition (difference)
The difference of two sets is a set that includes elements of the first set that are not included in the second. In programming, this operation is often called diff.
["kolya"]
Belonging to the multitude
You can check whether an element belongs to a set using the in_array function:
Task
There are two arrays, and you want to find their union (all elements, but if an element is in both arrays, it is counted once), intersection (elements in both arrays), or difference (elements in one array that are not in the other).
Solution
To define a union:
$union = array_unique(array_merge($a, $b));
To calculate the intersection:
$intersection = array_intersection($a, $b);
To find a simple difference:
$difference = array_diff($a, $b);
And to get the symmetric difference (exclusive OR):
Discussion
Many of the components required for such calculations are built into PHP; you just need to combine them in the appropriate sequence.
When a union is obtained from two arrays, one giant array is created with all the values of the original arrays. But the array_merge() function allows duplicate values when merging two numeric arrays, so you need to call the array_unique() function.
to filter out such elements.
However, this may result in gaps because the array_unique() function does not compact the array. However, this is not a problem because both the foreach statement and the each() function handle sparsely populated arrays without interference.
The function for calculating intersection is simply named array_intersection() and does not require any additional effort.
The array_diff() function returns an array containing all the unique elements of the $old array that are not in the $new array. This is called a simple difference:
$difference = array_diff($old, $new);
Array
=> not
=> to
)
The resulting $difference array contains "not" and "to" because array_diff() is case sensitive. It does not include the "whatever" element because it is not in the $old array.
To get the inverse difference, or, in other words, to find the unique elements of the $new array that are missing in the $old array, you need to swap the arguments:
$old = array("To", "be", "or", "not", "to", "be");
$new = array("To", "be", "or", "whatever");
$reverse_diff = array_diff($new, $old);
Array
=> whatever
)
The $reverse_diff array contains only the "whatever" element.
If you need to apply a function or other filter in the array_diff() function, embed your own difference (subtraction) algorithm:
// apply a case-insensitive subtraction algorithm; difference -i
$seen = array();
foreach ($new as $n) (
$seen++;
}
foreach ($old as $o) (
$o = strtolower($o);
if (!$seen[$o]) ( $diff[$o] = $o; )
}
The first foreach statement creates an associative array for further searching.
Then it loops through the $old array and, if the element is not found during the search, it is added to the $diff array.
This process can be speeded up by combining array_diff() and array_map() functions:
$diff = array_diff(array_map("strtolower", $old),
array_map("strtolower", $new));
The symmetric difference is what is in $a but not in $b, plus what is in $b but not in $a:
$difference = array_merge(array_diff($a, $b), array_diff($b, $a));
Once established, the algorithm moves forward. The array_diff() function is called twice and determines two differences. They are then combined into one array. There is no need to call array_unique() since these arrays were specifically designed to have no common elements.
These functions allow you to manipulate arrays in a variety of ways. Arrays are ideal for storing, modifying, and working with sets of variables.
Single- and multi-dimensional arrays are supported, both created by the user and returned as a result by some function. There are special functions for working with databases that make it easier to work with arrays of data returned as a result of executing queries; There are also functions that return arrays as results.
To learn more about how arrays are created and used in PHP, see the Arrays chapter of this tutorial.
Installation
There is no installation required to use these features as they are part of the PHP core.
Predefined Constants
The constants listed below are always available as part of the PHP core.
CASE_LOWER(integer)
CASE_LOWER used with function array_change_key_case() to indicate whether array keys should be converted to lowercase characters. Default function array_change_key_case() This constant is used.
CASE_UPPER(integer)CASE_UPPER used with function array_change_key_case() to indicate whether array keys should be converted to uppercase characters.
array_change_key_case -- Return an array whose character keys are converted to upper or lower case characters array_chunk -- Split an array into chunks array_combine -- Create a new array using one array as the keys and another as the corresponding values array_count_values -- Count the count of all values array_diff_assoc -- Calculate array divergence with additional index checking array_diff_key -- Compute array divergence by comparing keys array_diff_uassoc -- Compute array divergence with additional index checking performed using a user-defined function array_diff_ukey -- Compute array divergence using key comparison callback array_diff -- Calculate array divergence array_fill -- Fill an array with a specific value array_filter -- Apply a filter to an array using the array_flip callback -- Swap array values array_intersect_assoc -- Compute array convergence with additional index check array_intersect_key -- Calculate array intersection by comparing keys array_intersect_uassoc -- Calculate array intersection with additional index check done using user-defined function array_intersect_ukey -- Calculate array intersection using key comparison callback array_intersect -- Calculate array convergence array_key_exists -- Check whether the specified key or index is present in the array array_keys -- Select all keys in the array array_map -- Apply a callback function to all elements of the specified arrays array_merge_recursive -- Recursively merge two or more arrays array_merge -- Merge two or more arrays array_multisort -- Sort multiple arrays or multidimensional arrays array_pad -- Increase the size of an array to a given value array_pop -- Retrieve the last element of an array array_product -- Calculate the product of array values array_push -- Add one or more elements to the end of an array array_rand -- Select one or more random values from array_reduce -- Iteratively reduce an array to a single value using the callback function array_reverse -- Returns an array with elements in reverse order array_search -- Searches the array for a given value and returns the corresponding key if successful array_shift -- Retrieve the first element of the array array_slice - - Select a slice of an array array_splice -- Remove a sequence of array elements and replace it with another sequence array_sum -- Calculate the sum of array values array_udiff_assoc -- Calculate divergence in arrays with additional index checking, using the callback function array_udiff_uassoc to compare values -- Compute divergence in arrays with additional index checking, using the array_udiff callback function to compare values and indices -- Calculate array divergence using the array_uintersect_assoc callback function for comparison -- Calculate array intersection with additional index checking, using the array_uintersect_uassoc callback function to compare values -- Calculate array intersection with additional index checking using the array_uintersect callback to compare indices and values -- Calculate the intersection of arrays using the array_unique callback to compare values -- Remove duplicate values from an array array_unshift -- Add one or more elements to the beginning of the array array_values -- Select all values of an array array_walk_recursive -- Recursively apply a custom function to each element of the array array_walk -- Apply a custom function to each element of the array array -- Create an array arsort -- Sort the array in reverse order, preserving the keys asort -- Sort the array, preserving the keys compact -- Create an array containing variable names and their values