2

I have an array $rows where each element is a row of 15 tab-delimited values. I want to explode $rows into a 2D array $rowData where each row is an array element and each tab-delimited value is assigned to a different array element. I've tried these two methods without success. I know the first one has a coding error but I do not know how to correct it. Any help would be amazing.

for ($i=0; $i<count($rows); $i++){
    for ($j=0; $j<15; $j++){
    $rowData = array([$i] => array (explode("   ", $rows[$j])));
    }  
}  

foreach ($rows as $value){
    $rowData = array( array (explode("  ", $rows[$value])));  
}

2 Answers 2

5
$rowData = array();
foreach($rows as $value) {
  $rowData[] = explode("\t", $value);
}
Sign up to request clarification or add additional context in comments.

Comments

2
for ($j=0; $j<15; $j++) {
    $rowData[$j] = explode("\t", $rows[$j]);
}

To expand: The problem with the following code:

$rowData = array([$i] => array (explode("   ", $rows[$j])));

is that you don't appear to know what the different things you've written mean precisely.

A call to array() returns a new array with the indicated elements. So array (explode(" ", $rows[$j])) yields an array with a single element, namely the array returned by explode(). And you're wrapping that in another call to array(), specifying the loop variable $i as the key corresponding to that element. Also, you're using the assignment symbol =, which means that every time you go through the loop, $rowData is being completely overwritten - what you wanted was to add new elements to it without getting rid of the old ones.

1 Comment

Thank you for that explanation, I foolishly didn't realize I was even calling an array() function. Very informative!

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.