Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Convert String Matrix Into Multi-Dimensional Array

Tags:

arrays

php

matrix

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.

like image 425
Justin Avatar asked Mar 04 '26 15:03

Justin


1 Answers

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.

like image 61
kba Avatar answered Mar 07 '26 05:03

kba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!