Usage of associative arrays in PHP

Source: Internet
Author: User
Tags arrays shuffle

1. Adding array elements
PHP is a weak type language, which means you don't need to display an array and its size, instead, you can declare and populate the array at the same time.

The code is as follows Copy Code
$capitals = Array (
' Alabama ' => ' Montgomery ',
' Alaska ' => ' Juneau ',
' Arizona ' => ' Phoenix '
);

Additional array elements can be appended as follows:

$capitals [' Arkansas '] = ' Little rock '; If you are working on a digital index array, you may want to use the display named function to prepend and append elements, such as Array_push () and Array_unshift () functions, but these functions cannot manipulate associative arrays.

2. Delete array elements
If you want to remove an element from an array, use the unset () function, such as:

The code is as follows Copy Code
unset ($capitals [' California ']);

When you use a numeric index array, you can remove an array element more and more flexibly, using the Array_shift () and Array_pop () functions to remove an element from the beginning and end of the array, respectively.

3. Exchange keys and values
Suppose you want to create a new array called $states, use the state House as an index, use the state name as the associated value, and use the Array_flip () function to easily accomplish this task.

The code is as follows Copy Code
$capitals = Array (
' Alabama ' => ' Montgomery ',
' Alaska ' => ' Juneau ',
' Arizona ' => ' Phoenix '
);
$states = Array_flip ($capitals);
$states = Array (
' Montgomery ' => string ' Alabama ',
' Juneau ' => string ' Alaska ',
' Phoenix ' => string ' Arizona '
// );

4, merging arrays
Assuming that the preceding array is used by a web-based "flashcard" service, you want to provide a way to test students ' mastery of the state capitals of the United States, you can use the Array_merge () function to merge arrays that contain states and capitals.

The code is as follows Copy Code


$stateCapitals = Array (
' Alabama ' => ' Montgomery ',
' Alaska ' => ' Juneau ',
' Arizona ' => ' Phoenix '
);
$countryCapitals = Array (
' Australia ' => ' Canberra ',
' Austria ' => ' Vienna ',
' Algeria ' => ' Algiers '
);
$capitals = Array_merge ($stateCapitals, $countryCapitals);

5. Edit Array values
Assuming that the data in the array contains case errors, and you want to correct the errors before inserting them into the database, you can use the Array_map () function to apply a callback to each array element.

The code is as follows Copy Code


Function capitalize ($element)
{
$element = Strtolower ($element);
Return Ucwords ($element);
}
$capitals = Array (
' Alabama ' => ' MontGoMEry ',
' Alaska ' => ' Juneau ',
' Arizona ' => ' PhoeniX '
);
$capitals = Array_map ("capitalize", $capitals);

6, the key to the array of sorting
Flashcard programs often use a variety of sorts, such as alphabetical order, and you can use the Ksort () function key to sort the associative array.

The code is as follows Copy Code

$capitals = Array (
' Arizona ' => ' Phoenix ',
' Alaska ' => ' Juneau ',
' Alabama ' => ' Montgomery '
);
Ksort ($capitals);

Because arrays are passed by arguments to the Ksort () function, you no longer need to assign the result of the order to another variable.

7, random array ordering
Another random sort technique is involved in the Flashcard program, where you use the shuffle () function to implement the random ordering of the array items.

The code is as follows Copy Code

$capitals = Array (
' Arizona ' => ' Phoenix ',
' Alaska ' => ' Juneau ',
' Alabama ' => ' Montgomery '
);
Shuffle ($capitals);

If you don't need to scramble the array order, you just want to randomly select a value, then use the Array_rand () function.

8, determine whether the key and value exist
You can use the In_array () function to determine whether an array element exists.

The code is as follows Copy Code

$capitals = Array (
' Arizona ' => ' Phoenix ',
' Alaska ' => ' Juneau ',
' Alabama ' => ' Montgomery '
);
if (In_array ("Juneau", $capitals))
{
echo "exists!";
} else {
echo "does not exist!";
}

Few people know that this function can also determine whether an array key exists, and at this point it is the same as the function of the array_key_exists () function.

The code is as follows Copy Code
$capitals = Array (
' Arizona ' => ' Phoenix ',
' Alaska ' => ' Juneau ',
' Alabama ' => ' Montgomery '
);
if (array_key_exists ("Alaska", $capitals))
{
echo "Key exists!";
} else {
echo "Key does not exist!";
}

9. Search Array
You might want to search for array resources so that users can easily retrieve the associated States with a particular state, and you can do array searches by using the Array_search () function.

The code is as follows Copy Code


$capitals = Array (
' Arizona ' => ' Phoenix ',
' Alaska ' => ' Juneau ',
' Alabama ' => ' Montgomery '
);
$state = Array_search (' Juneau ', $capitals);
$state = ' Alaska '

10. Standard PHP Library
The standard PHP library (Standard PHP LIBRARY,SPL) provides developers with a number of data structures, iterators, interfaces, exceptions, and other features not available in previous PHP languages that allow you to traverse an array through object-oriented syntax.

The code is as follows Copy Code


$capitals = Array (
' Arizona ' => ' Phoenix ',
' Alaska ' => ' Juneau ',
' Alabama ' => ' Montgomery '
);
$arrayObject = new Arrayobject ($capitals);
foreach ($arrayObject as $state => $capital)
{
printf ("The capital of%s is%s<br/>", $state, $capital);
}
The capital of Arizona is Phoenix
The capital of Alaska is Juneau
The capital of Alabama is Montgomery

Three ways to traverse an associative array:

Foreach

The code is as follows Copy Code
<?php
$sports = Array (
' Football ' => ' good ',
' Swimming ' => ' very ',
' Running ' => ' not good '
);

foreach ($sports as $key => $value) {
echo $key. ":". $value. " <br/> ";
}
?>

Program Run Result:

Football:good

Swimming:very.

Running:not Good


each

The code is as follows Copy Code

<?php
$sports = Array (
' Football ' => ' good ',
' Swimming ' => ' very ',
' Running ' => ' not good '
);

while ($elem = each ($sports)) {
echo $elem [' key ']. ":". $elem [' value ']. " <br/> ";
}
?>

Program Run Result:

Football:good
Swimming:very.
Running:not Good

List & each

The code is as follows Copy Code

<?php
$sports = Array (
' Football ' => ' good ',
' Swimming ' => ' very ',
' Running ' => ' not good '
);

while (the list ($key, $value) = each ($sports)) {
echo $key. ":". $value. " <br/> ";
}
?>

Program Run Result:

Football:good
Swimming:very.
Running:not Good


Hash table = Hash table


There is a list of user names, stored 10,000 user names, no duplicates;
There is also a list of blacklist, stored 2000 user names, the format and user name list is the same;
Now you need to remove the username from the list of user names in the blacklist and ask to be processed as quickly as possible.

This problem is a small amount of processing, if the actual point, 2 tables can be very large, such as 200 million records.

I first thought of the method is to do a nested loop, set the user name table has M record, blacklist list has N records, then, the number of cycles is M * N times!
PHP Version Code:

The code is as follows Copy Code
<?php
foreach ($arrayM as $keyM => $nameM) {
foreach ($arrayN as $nameN) {
if ($nameM = = $nameN) {
The bank executed the M * N times!
Unset ($arrayM [$keyM]);
}
}
}
return $arrayM;
?>

Another way to take advantage of an array index.

PHP is a weak type of language and does not have a strict variable-type limit like the C language. The C language array, each element must be of the same type, and the index starts at 0.
An array of PHP, which can be indexed as a string, also known as an associative array.
Array index, there is a natural limit is not repeat, and access time does not need to find, you can directly locate.

Or the question that we have just now, we have adopted another approach.

The user name of the blacklist list is organized into an array, and the index of the array is the username.

Then, to traverse the list of users, just use Isset to query whether the user name exists.

PHP Version Code:

The code is as follows Copy Code

<?php
$arrayHash = Array ();
foreach ($arrayN as $nameN) {
The bank executed N times.
$arrayHash [$nameN] = 1;
}

foreach ($arrayM as $keyM => $nameM) {
if (Isset ($arrayHash [$nameM])) {
The bank executed M times!
Unset ($arrayM [$keyM]);
}
}
return $arrayM;
?>

You can see that the optimized code, the number of cycles is M + N times.

If M and N are 10000, the optimization before the cycle of 100 million times, after optimization, only 20,000 times, the difference is 5,000 times times!
If the second program takes 1 seconds, the first program requires nearly 1.5 hours

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.