Home  >  Article  >  Backend Development  >  How to scramble associative array in php

How to scramble associative array in php

藏色散人
藏色散人Original
2018-11-22 11:00:063208browse

This article mainly tells you how PHP disrupts associative arrays.

Recommended reference tutorial: "PHP Tutorial"

For PHP learners, when it comes to disrupting arrays, the shuffle function may be the first thing that comes to mind. But how to solve the problem of disrupting the associative array and retaining the key-value pairs may be difficult.

Below we will combine specific code examples to introduce to you how php disrupts the associative array and maintains the key-value pair.

The specific solution code example is as follows:

<?php
function shuffle_assoc($my_array)
{
    $keys = array_keys($my_array);

    shuffle($keys);

    foreach($keys as $key) {
        $new[$key] = $my_array[$key];
    }

    $my_array = $new;

    return $my_array;
}

$colors = array("color1"=>"Red", "color2"=>"Green", "color3"=>"Yellow");
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r(shuffle_assoc($colors));

The effect is as shown in the figure below:

How to scramble associative array in php

As shown in the figure, every time we refresh Shuffle once, and the original key-value pairs remain unchanged.

Note:

1. array_keys() function Returns a new array containing all the key names in the array.

Syntax:

array_keys(array,value,strict)

If the second parameter is provided, only the key name with the key value is returned. If the strict parameter is specified as true, PHP will use equality comparison (===) to strictly check the data type of the key value.

2. shuffle() function Rearranges the elements in the array in random order. This function assigns new key names to elements in the array. Existing key names will be deleted.

This article is an introduction to the method of PHP disrupting associative arrays. It is also very simple and easy to understand. I hope it will be helpful to friends in need!

The above is the detailed content of How to scramble associative array in php. 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