Functions for working with arrays. Set Theory - PHP: Arrays - Hexlet

These functions allow you to operate on arrays in a variety of ways. Arrays are ideal for storing, modifying, and manipulating sets of variables.

One-size and multi-size 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 queries; there are also functions that return arrays as a result.

For more information on how arrays are created and used in PHP, see the Arrays chapter of this guide.

Installation

These functions do not require installation 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 specify whether to convert array keys 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 specify whether to convert array keys to uppercase characters.

array_change_key_case -- Returns an array whose character keys have been converted to upper or lower case characters array_chunk -- Split array into parts array_combine -- Create a new array using one array as keys and another as corresponding values ​​array_count_values ​​-- Count the number of all values array_diff_assoc -- Calculate array divergence with additional index check array_diff_key -- Calculate array divergence by comparing keys array_diff_uassoc -- Calculate array divergence with additional index check performed by a user-defined function array_diff_ukey -- Calculate array divergence using callback function for comparing keys array_diff -- Calculate discrepancy in arrays 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 -- Calculate convergence of arrays with additional index check array_intersect_key -- Compute array intersection by comparing keys array_intersect_uassoc -- Compute array intersection with additional index check performed by user-defined function array_intersect_ukey -- Compute array intersection using key comparison callback function array_intersect -- Compute array convergence array_key_exists -- Check whether the specified key or index is present in the array array_keys -- Select all keys of the 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 -- Increment array size to given value array_pop -- Extract last element of array_product -- Calculate product of array values ​​array_push -- Append one or more elements to end of array_rand -- Select one or more random values ​​from array_reduce -- Iteratively reduce an array to a single value using the callback array_reverse -- Returns an array with elements in reverse order array_search -- Searches for a given value in an array and returns the corresponding key if successful array_shift -- Retrieve the first element of an array array_slice - - Select a slice of the 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 discrepancy in arrays with additional index checking, using the array_udiff_uassoc callback function to compare values ​​-- Calculate discrepancy in arrays with additional index check, using the array_udiff callback to compare values ​​and indices -- Calculate array discrepancy, using array_uintersect_assoc callback to compare -- Calculate array intersection with additional index checking, using array_uintersect_uassoc callback to compare values ​​-- Calculate array intersection with additional index check, 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 array_values ​​-- Select all values ​​in array_walk_recursive -- Recursively apply a user-defined function to each element of array_walk -- Apply a user-defined function to each member of 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

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 of one array that are not present in the other).

Solution
To define a join:
$union = array_unique(array_merge($a, $b));

To calculate an intersection:
$intersection = array_intersection($a, $b);

To find the 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 resolves duplicate values ​​when merging two numeric arrays, so you need to call the array_unique() function,
to filter out such items.

But this can create gaps because the array_unique() function does not compact the array. However, this is not difficult, since both the foreach statement and the each() function handle sparsely filled arrays without interference.

The function to calculate the intersection is simply named array_intersection() and requires no extra 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 simple difference:


$difference = array_diff($old, $new);
array
=> not
=> to
)

The resulting $difference array contains "not" and "to" because the array_diff() function 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, find unique elements of the $new array that are not 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 algorithm for finding the difference (subtraction):

// 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 the 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. Then they are combined into one array. There is no need to call the array_unique() function, as these arrays have been specifically designed to have no elements in common.

Set theory. I know how many people are afraid of mathematics, but specifically the theory of sets (naive) is very simple and understandable. Moreover, we constantly use its elements in everyday life. And in programming, it is found at every step.

The basic concept of set theory, surprisingly, is a bunch of. A set denotes a set of objects of an 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 the set has a finite number of elements.

An example of an infinite set is the 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(in relation 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 set objects. 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 set of any objects that we want to consider as a whole.

The main thing for us in the theory of sets 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 is the set obtained as the intersection of the original sets of friends.

Moving on to programming, you can see that an array is very similar to a set, and indeed it can be considered that way. Why is it so important? By understanding the principles behind some operations, you will be able to 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 a 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 (set union: coll1 + coll2).

Separately, it should be said 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 will get to know them later.

Consider the basic operations:

intersection

An intersection of sets is a set that includes elements that occur 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 the elements of all given sets. The union of sets in php cannot be done in 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"]

Complement (difference)

The difference of two sets is the set that includes elements of the first set that are not included in the second. In programming, this operation is often called diff.

["kolya"]

Set membership

You can check whether an element belongs to a set using the in_array function:

 
Articles By topic:
Pasta with tuna in creamy sauce Pasta with fresh tuna in creamy sauce
Pasta with tuna in a creamy sauce is a dish from which anyone will swallow their tongue, of course, not just for fun, but because it is insanely delicious. Tuna and pasta are in perfect harmony with each other. Of course, perhaps someone will not like this dish.
Spring rolls with vegetables Vegetable rolls at home
Thus, if you are struggling with the question “what is the difference between sushi and rolls?”, We answer - nothing. A few words about what rolls are. Rolls are not necessarily Japanese cuisine. The recipe for rolls in one form or another is present in many Asian cuisines.
Protection of flora and fauna in international treaties AND human health
The solution of environmental problems, and, consequently, the prospects for the sustainable development of civilization are largely associated with the competent use of renewable resources and various functions of ecosystems, and their management. This direction is the most important way to get
Minimum wage (minimum wage)
The minimum wage is the minimum wage (SMIC), which is approved by the Government of the Russian Federation annually on the basis of the Federal Law "On the Minimum Wage". The minimum wage is calculated for the fully completed monthly work rate.