10 tips for working with arrays in PHP

Source: Internet
Author: User
Tags spl
Associative arrays are a type of data that is often used when describing a set of keys and their associated values, which can be said to be the backbone of all programming languages, and of course, PHP is no exception, in fact, associative arrays are very important to web development tasks, and PHP supports a variety of ways to manipulate associative arrays, for developers, To figure out the most effective way to manipulate these arrays, the most appropriate method to develop your own program.

This article will cover 10 tips for manipulating PHP associative arrays, and skilled use can help you improve your development efficiency.

1. Adding array elements

PHP is a weakly typed 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.

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

Additional array elements can be appended as follows:

If you are working with a numeric index array, you may want to use the display named function to prepend and append elements, such as the 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:

7 unset ($capitals [' California ']);

When using numeric indexed arrays, there are more and more flexible ways to delete array elements, and you can use the Array_shift () and Array_pop () functions to remove an element from the beginning and end of an array, respectively.

3. Exchange keys and values

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

$capitals = Array (   ' Alabama ' = ' Montgomery ',   ' Alaska ' = '  Juneau ',    ' Arizona ' = ' Phoenix ')  );  $states = Array_flip ($capitals);  $states = Array (  //  ' Montgomery ' = + string ' Alabama ',  //  ' Juneau ' = =     string ' Alaska ', c13/>//  ' 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 U.S. state capitals, you can use the Array_merge () function to merge the arrays that contain the state and capital.

$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, you want to correct these errors before inserting into the database, you can use the Array_map () function to apply a callback to each array element.

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


6. Sort the keys in an array

Flashcard programs often use various sorts, such as alphabetical order, and you can use the Ksort () function keys to sort the associative array.

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

Because the array is passed to the Ksort () function by argument, it means that you no longer need to assign the sort result to another variable.

7. Random array sorting

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

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

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

8. Determine if the key and value exist

You can use the In_array () function to determine whether an array element exists.

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

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

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

9. Searching arrays

You might want to search the array resources so that users can easily retrieve the associated state with a specific state, and you can use the Array_search () function to implement an array search.

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

10. Standard PHP Library

Standard PHP LIBRARY,SPL provides developers with a number of data structures, iterators, interfaces, exceptions, and other features not previously available in the PHP language, which can be used to iterate through an array using object-oriented syntax.

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

This is just one of the many great features of SPL, be sure to read the PHP documentation for more information.

  • Large-Scale Price Reduction
    • 59% Max. and 23% Avg.
    • Price Reduction for Core Products
    • Price Reduction in Multiple Regions
    undefined. /
    Connect with us on Discord
    • Secure, anonymous group chat without disturbance
    • Stay updated on campaigns, new products, and more
    • Support for all your questions
    undefined. /
    Free Tier
    • Start free from ECS to Big Data
    • Get Started in 3 Simple Steps
    • Try ECS t5 1C1G
    undefined. /

    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.