0

I'm new to PHP so I'm not sure how to optimize this code.

I execute a Python script from PHP and the $output variable returned is an array of arrays.

exec (" /Users/$USER/anaconda/bin/python /Applications/MAMP/cgi-bin/Evaluation1.py",$output)

Each array within the $output array contains one string value separated by commas. So $output is Array ( [0] => 1, 好, 0 [1] => 2, 妈妈, 3), etc.

In each array within the $output array, I use explode on the string value to create an array, and add it to my new $output array called $output2

$output2 = array();
foreach($output as $value){
$myArray = explode(',', $value);
$output2[] = $myArray;
}

Is there a way to just replace/overwrite the string value in the arrays within $output with the new array, instead of adding each item to a new $output2 array?

0

2 Answers 2

2

You could use array_walk to do the loop over output. You pass in a callback function that is called for each value by reference so any changes to the passed in value stick to the array.

Test data:

$output = array(
    '1,A,2',
    '2,B,3',
    '3,C,4'
);

PHP >= 5.3.0

array_walk($output, function(&$val){ $val = explode(',', $val); } );

Older PHP

function mySplit(&$val){
    $val = explode(',', $val);
}
array_walk($output, 'mySplit');

Both output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => A
            [2] => 2
        )

    [1] => Array
        (
            [0] => 2
            [1] => B
            [2] => 3
        )

    [2] => Array
        (
            [0] => 3
            [1] => C
            [2] => 4
        )

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

Comments

1

Some great answers already. Just adding this for completeness.

$ar = array(
    "1,2,3",
    "4,5,6"
);

foreach($ar as $k => $v) {
    $ar[$k] = explode(',', $v);
}

Wold be interesting to see a a performance difference of the different methods although i doubt it would be much.

2 Comments

I was actually curious about the benchmarks also so I wrote/ran a little test. Over 1000 iterations, my code with anonymous function: 32.21ms, my code with defined function:27.76ms, your code: 21.27ms, derp's code: 28.17ms. You can click on the links to see each test. While they are all close together and the difference is negligible, I think it is interesting that the anony function does offer a little overhead with your foreach winning.
@JonathanKuhn awesome! thanks for running the tests.

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.