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

Undress AI Tool
Undress images for free

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

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

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

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez
