Caleb Oki Caleb Oki - 2 months ago 10
PHP Question

How can I create a matrix so I can access each number from the array like so $array[$key]

I am trying to create a multi-dimensional array from a text file so I can access each number. For example the first 7 would be $triangle[0][0] and the first 5 would be $triangle[0][1]. The code I've written so far is

<?php
$triangles = explode("\n", file_get_contents('18.txt'));
var_dump($triangles);
?>


This produced the following output. What do I need to change here? Thanks

array (size=15)
0 => string '75' (length=3)
1 => string '95 64' (length=6)
2 => string '17 47 82' (length=9)
3 => string '18 35 87 10' (length=12)
4 => string '20 04 82 47 65' (length=15)
5 => string '19 01 23 75 03 34' (length=18)
6 => string '88 02 77 73 07 63 67' (length=21)
7 => string '99 65 04 28 06 16 70 92' (length=24)
8 => string '41 41 26 56 83 40 80 70 33' (length=27)
9 => string '41 48 72 33 47 32 37 16 94 29' (length=30)
10 => string '53 71 44 65 25 43 91 52 97 51 14' (length=33)
11 => string '70 11 33 28 77 73 17 78 39 68 17 57' (length=36)
12 => string '91 71 52 38 17 14 91 43 58 50 27 29 48' (length=39)
13 => string '63 66 04 68 89 53 67 30 73 16 69 87 40 31' (length=42)
14 => string '04 62 98 27 23 09 70 98 73 93 38 53 60 04 23' (length=44)

Answer

You can use file to get the contents of the file into an array where each array element is a line from the file, then map str_split over that array to separate each line into individual characters.

$triangles = array_map('str_split', file('18.txt',  FILE_IGNORE_NEW_LINES ));

echo $triangles[0][0];    // outputs 7
echo $triangles[0][1];    // outputs 5

If you don't want the spaces, you can use str_replace to remove them before splitting the line into individual characters.

$triangles = array_map(function($line) {
    return str_split(str_replace(' ', '', $line));
}, file('18.txt',  FILE_IGNORE_NEW_LINES ));