4
$transData = fgets($fp);
while (!feof ($fp))
{  
    $transArry = explode(" ", $transData);
    $first = $transArry[0];
    $last = $transArry[1];
    $Sub = $transArry[2];
    $Grade= $transArry[3]; 
    echo "<table width='400' ><colgroup span='1' width='35%' /><colgroup span='2' width='20%' /> <tr><td> ".$first."  ".$last." </td><td>   ".$Sub." </td><td> ".$Grade." </td></tr></table>";
    $transData = fgets($fp);
}

My teacher wants me to change this use of explode() to str_split() while keeping the same output. How do I do this?

Mark Elliot
  • 75,278
  • 22
  • 140
  • 160
user289346
  • 487
  • 2
  • 6
  • 7

2 Answers2

3

If you use str_spilt you can't use the delimiter. str_split splits the string character by character and stored into each array index.And also using str_split() we can specify the limit of the string to store in array index. If you use split() function only, you can get the same output, what explode() did.

Instead of explode use the following line.

$transArry = split(" ",$transData);
rekha_sri
  • 2,677
  • 1
  • 24
  • 27
  • 4
    Note: `split` is deprecated as of PHP 5.3; `preg_split` and `explode` are the recommended alternatives (the former for if you need a regex, the latter for splitting by a normal string). – cHao May 28 '13 at 19:27
2

The difference between the two explode() and str_split() is that explode uses a character to split on and the the str_split requires the number of characters. So unless the fields in the record data $transData are exactly the same length, this will require additional code. If all fields/records are of the same length, you can just drop in the function. So if each field in the record is 10 characters long, you can do:

$transArry = str_split($transData, 10);
Chuck Burgess
  • 11,600
  • 5
  • 41
  • 74