Current Location: Home> Latest Articles> Use with exploit: convert strings into key-value arrays

Use with exploit: convert strings into key-value arrays

M66 2025-06-06

In PHP, we often need to process strings into arrays and convert them into arrays of key-value pairs. The array_fill_keys function is a very practical function that can help us generate an array of key-value pairs based on elements of an array and fill in the specified value for each key. This article will use an example to explain how to split a string into an array, and use array_fill_keys to convert the split array into a key-value pair array.

Step Analysis

1. Use the exploit function to split the string

First, we need to split a string into an array. PHP provides the exploit() function, which can split strings into arrays based on specified delimiters.

For example, suppose we have a string containing some comma-separated words:

 $string = "apple,banana,orange,grape";

Use the exploit() function to split it into an array:

 $array = explode(",", $string);
print_r($array);

The output result is:

 Array
(
    [0] => apple
    [1] => banana
    [2] => orange
    [3] => grape
)

2. Use array_fill_keys to convert to key-value pair arrays

Next, we will use the array_fill_keys function to convert the split array into an array of key-value pairs. array_fill_keys requires two parameters: the first is the key name array, and the second is the filled value.

We can use the split array as the key name array and specify the same value for each key, for example, setting the value of all keys to true .

 $keys = explode(",", $string);
$values = true; // All key-value pairs are set to true

$assocArray = array_fill_keys($keys, $values);
print_r($assocArray);

The output result is:

 Array
(
    [apple] => 1
    [banana] => 1
    [orange] => 1
    [grape] => 1
)

3. Combine instances and URLs

If we are also involved in URLs while processing strings, we may use these methods to split the URL string, and then we can use array_fill_keys to fill the key-value pairs.

Suppose we have the following URL:

 $url = "https://m66.net/product?id=123&category=books&price=99";

We can split the parameter parts in the URL and convert them into key-value pair arrays:

 // SplitURLquery string part
$queryString = parse_url($url, PHP_URL_QUERY);
parse_str($queryString, $params);

// use array_fill_keys Create an array of key-value pairs
$keys = array_keys($params);
$values = 'some_value'; // Set the value of all keys to 'some_value'

$assocArray = array_fill_keys($keys, $values);
print_r($assocArray);

The output result is:

 Array
(
    [id] => some_value
    [category] => some_value
    [price] => some_value
)

In this example, we convert them into a key-value pair array by parsing the URL and extracting the key names of the query parameters.