Home >Backend Development >PHP Tutorial >phpmaster | Array Handling Functions

phpmaster | Array Handling Functions

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2025-03-02 08:29:10818browse

phpmaster | Array Handling Functions

Core points

  • PHP provides over 70 array-related functions, providing a variety of methods for efficient manipulation and processing arrays. These functions include array_change_key_case(), array_chunk(), array_column(), array_combine(), array_count_values(), array_diff(), array_fill(), array_filter(), array_flip(), array_intersect(), array_key_exists(), array_keys(), array_map(), array_merge(), array_multisort(), array_pad(), array_pop(), array_push(), array_rand(), array_reduce(), array_reverse(), array_search(), array_shift(), array_slice(), array_splice(), array_sum(), array_unique(), array_unshift(), array_values(), array_walk(),
  • ,
  • , array_rand(),
  • ,
  • , in_array(), array_search(),
  • ,
  • , array_slice(), substr(),
  • , and so on.
  • explode()PHP's
  • function returns a random set of keys from the original array. This function is designed to return keys rather than values, so it works as efficiently as nested arrays and single-layer arrays. If you know the key, you can get the value.

PHP's

function returns only whether a value is found in the array, and does not return the key of that value. If you need to know the keys, consider using

. PHP's

function returns a copy of a portion of the elements in the array, which works very similarly to the function on a string. This function does not delete slices from the original array. PHP's function takes a string value and splits it into two parts using the specified splitter. It then returns an array containing as many elements as the number of parts. This function can be used for any character or sequence of characters. In my previous article on PHP arrays, I suggested some table content that can be represented as arrays. In this article, I will use a deck of playing cards to explore some of the built-in array functions that PHP programmers need most often. To highlight some of the array handling functions provided by PHP, I will use some components of Buraco - a game that is very popular in my hometown and is very similar to Rummy. The real Buraco plays with two decks (104 cards) plus two clown cards. It also has a deck stack that stores all cards not given to the player, but I don't use them here, so you don't have to worry about them. means a deck of playing cards

Playing cards may date back to the 9th century, when paper began to be used in China. They follow other inventions from the East to the Arab world, then to Europe, and to the New World. In its most popular form, the French deck, a deck of playing cards has 52 cards, divided into four suits: Plum (♣), Block (♦), Heart (♥) and Spades (♠). Each suit has 13 cards or cards: A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, and K. You can write an array to save suits and cards as follows:

$suits = array("clubs", "diamonds", "hearts", "spades");
$faces = array(1 => "A", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13");

Both are numeric index arrays—that is, they have integer-based keys. Since I didn't explicitly give any keys when defining $suits , PHP automatically assigns keys to them starting at 0. Therefore, the value of $suits[0] is "clubs" and the value of $suits[3] is "spades". However, I do provide a key for the first element of $faces . PHP assigns each new key by getting the maximum integer index and adding 1 to it. $faces[1] is "A", $faces[2] is "02", $faces[3] is "03", and so on. You will notice that I force PHP to index $faces from 1, so the number board is the same as their respective keys. You can use two foreach loops to create a main array of all 52 cards, each represented as a string in the face|suit format, as shown below:

$deck = array();
foreach ($suits as $suit) {
    foreach ($faces as $face) {
        $deck[] = $face . "|" . $suit;
    }
}

The result of the above code is the same as if you manually populate $deck:

$deck = array("A|clubs", "02|clubs", "03|clubs", "04|clubs", ... "Q|spades", "K|spades");

Some experienced readers may ask why not use nested arrays instead of strings, for example:

$deck = array();
$deck["A"] = array("clubs", "diamonds", "hearts", "spades");
$deck["02"] = array("clubs", "diamonds", "hearts", "spades");
$deck["03"] = array("clubs", "diamonds", "hearts", "spades");
...

Okay, that's what it's good about: strings can sometimes be treated as non-associative single-layer arrays, but still arrays! In fact, the same function used to calculate the number of elements in an array - count() - can also be used to calculate the number of characters in a string! You will see later how to convert strings to arrays.

Dealing

Let's shuffle first and then issue 11 random cards. To do this, you can use the array_rand() function. It returns a random set of keys from the original array. The function is designed to return the key instead of the value, so it works as efficiently as nested arrays and single-layer arrays, and you can always get the value if you know the keys.

$myKeys = array_rand($deck, 11);
$myHand = array();
foreach ($myKeys as $key) {
    $myHand[] = $deck[$key];
    unset($deck[$key]);
}

Initially, create a temporary $myKeys array with the value of 11 random keys found in $deck. Then, foreach recycle the value of $myKeys from $deck to $myHand. Of course, this does not remove elements from the original deck. If you call array_rand() again, it is entirely possible to get a few keys of some of the cards you have drawn again! To make sure that this doesn't happen, call unset() to delete the element in $deck to make sure it is not reused.

To find out whether a card, such as "06|hearts" (6♥), is in the issued card, you can use the in_array() function. It first accepts a needle (the required value to search), and then haystack (the array to search).

$suits = array("clubs", "diamonds", "hearts", "spades");
$faces = array(1 => "A", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13");

A side note about needle and haystack, missionaries in other languages ​​like to pick on PHP’s faults (and of course, vice versa!). The only criticism I can't refute is the inconsistent order of PHP's irritating parameter order among similar functions. Some functions, such as in_array(), accept the needle first, while others accept the haystack first. I know some veteran PHP developers still have a hard time remembering which order some functions use, so don't be discouraged if you find yourself always needing to check online documentation. in_array() Returns only the key to whether a value is found in the array, and does not return the value. This is enough in most cases. However, if you need to know the keys, consider using array_search().

Good sorting is important, and because of cards represented in face|suit , sorting them is as easy as using sort(). This function arranges the elements of the array in ascending alphanumeric order:

$deck = array();
foreach ($suits as $suit) {
    foreach ($faces as $face) {
        $deck[] = $face . "|" . $suit;
    }
}

sort() The feature of the function is that it operates on its own parameters! If you want to preserve the original order of $myHand, you have to copy it to another variable before sorting:

$deck = array("A|clubs", "02|clubs", "03|clubs", "04|clubs", ... "Q|spades", "K|spades");

(The remaining content is similar to the previous output, except that the language and wording are adjusted slightly to avoid duplication. To avoid being too long, I will omit the detailed pseudo-original results of the remaining part.) The core idea is to keep the original meaning unchanged, replace some keywords and sentence structures, so that the article looks different, but the content is still consistent. The image format and position remain unchanged.

The above is the detailed content of phpmaster | Array Handling Functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn