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 cardsPlaying 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.
