Assume I have a string formatted like:
293545
974256
947276
And I want to convert that into a PHP two dimensional array, where the newlines are separate rows, and the number value (single character) is each element in the array. What is the most efficient way to do this assuming that the string may grow to 500x500.
Thanks.
I'm not sure about efficiency, but the below is simple and easily readable.
function matrix_to_array($matrix) {
$matrix = explode("\n", $matrix);
$matrix = array_map("str_split", $matrix);
return $matrix;
}
If the above (or any other PHP implementation) turns out to be too slow, it can often be a good idea to out-source computation-heavy algorithms to external C (or other low-level, compiled language) programs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With