-4

I have this array :

Array ( 
    [0] => SecRuleEngine On 
    [1] => SecRequestBodyAccess On
)

How to turn the array above into this:

Array ( 
    [0] => 
        Array ( 
            [0] => SecRuleEngine 
            [1] => On
        ) 
        [1] => Array ( 
            [0] => SecRequestBodyAccess 
            [1] => On
        )
   )
2

5 Answers 5

3

You can use array_map to achieve such a result, as shown below:

<?php
    # The initial array with its string elements.
    $array = ["SecRuleEngine On", "SecRequestBodyAccess On"];

    # Explode each element at the space producing array with 2 values.
    $new_array = array_map(function ($current) {
        return explode(" ", $current);
    }, $array);

    # Print the new array.
    var_dump($new_array);
?>

Here is a live example illustrating the above solution.

Sign up to request clarification or add additional context in comments.

Comments

0

This code will do what you want. It processes each entry in the input array in turn and uses explode to turn each value into an array of two values, the first being the part of the input value to the left of the space, and the second being the part to the right i.e. 'SecRuleEngine On' is transformed to ['SecRuleEngine', 'On'].

$input = array('SecRuleEngine On', 'SecRequestBodyAccess On');
$output = array();
foreach ($input as $in) {
    $output[] = explode(' ', $in);
}
print_r($output);

output:

Array
(
    [0] => Array
        (
            [0] => SecRuleEngine
            [1] => On
        )

    [1] => Array
        (
            [0] => SecRequestBodyAccess
            [1] => On
        )

)

2 Comments

Not me but I can see why, it crossed my mind to do so also. You have no explanation or comment to your code. That is not a proper answer
@Andreas fair comment. It was a bit rushed. I've added an explanation.
0

This will give you the exact result as you want. Just try this:

$input = ['SecRuleEngine On', 'SecRequestBodyAccess On'];
$output = [];
foreach($input as $item){
    array_push($output,explode(' ',$item));
}

print_r($output);

Comments

-1

You have to iterate over each item, then use it to create a new array:

$input = ['SecRuleEngine On', 'SecRequestBodyAccess On'];
$output = [];
foreach($input as $item)
{
    $keyval = explode(' ', $item);
    $output[] = [$keyval[0]=>$keyval[1]];
}

Comments

-1

Use array_map().

$array = ['SecRuleEngine On', 'SecRequestBodyAccess On'];

$new_array = array_map(function($item){ return explode(' ', $item); },  $array);

print_r($new_array);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.