Jump to content

Need to try and simplify my code possibly into two functions and I want to be able to use substr and strpos and store them into an array?


Ungond

Recommended Posts

Here's the code so far, essentially I want to. E able to take the text file that has numbers and commas and remove the commas, not happy with it would rather it be simpler in a away but with out the use of explode. Any help would be brilliant. Thank you

 

 

<?php

//linking table to form

$studentid=$_POST["id"];

 

//To print out student ID

echo "You have selected Student ID: $studentid <br />";

 

 

//define what the file equals to which is the students ID

$file = "$studentid.txt";

 

//Opening the selected files

$fileopen = fopen($file,'r') or die("Sorry, cannot open $file");

if($fileopen){

 

while (($buffer=fgets($fileopen,4096))!==false){

// echo $buffer."<br/>";

}

if(!feof($fileopen)){

echo "Error:unexpected fgets() fail\n";

 

}

fclose($fileopen);

}

 

//remove all commas from txt file

$filearray=file("$studentid.txt");

$count=count($filearray);

 

for($i=0; $i<$count; $i++){

 

$startnum=0;

$stringlength = strlen($filearray[$i]);

$comma = strpos($filearray[$i], ",", $startnum);

$array[$i][0] = substr($filearray[$i], $startnum, $comma);

$j=1;

 

while ($j<$count-1){

$comma = strpos($filearray[$i], ",", $startnum);

$comma2 = strpos($filearray[$i], ",", $comma+1);

$sub = $comma2-$comma;

$num = substr($filearray[$i], $comma+1, $sub -1);

$startnum = $comma2;

$array[$i][$j]= $num;

 

$j++;

}

$stop = $stringlength - $comma2;

$array[$i][$j] = substr ($filearray[$i], $comma2 + 1, $stop);

}

 

function array_transpose($filearray)

{

array_unshift($filearray, NULL);

return call_user_func_array('array_map', $filearray);

}

 

//table heading

echo"<h1>The Table</h1>";

 

//creating the rows and columns for the txt file

echo "<table border = 1 >";

for($row=0; $row<$count; $row++){

print "<tr>";

 

for($col=0; $col<$count; $col++){

print "<td>".$array[$row][$col]."</td>";

}

}

echo "</table>";

 

 

 

//table heading

echo"<h1>Transpose</h1>";

 

?>

Link to comment
Share on other sites

If, as you seem to be saying, all you want to do is "remove commas", why not use the str_replace function???  You can replace any comma with a null character (simply '') and write out a new file (perhaps) with the modified lines.

 

Plus - this code is really not doing much.  You do a loop thru the file (that is currently not producing anything) and then you check if you are at eof.  What's that for?

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.