Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I make this PHP code more efficient? (Editing a line in a CSV file)
    primarykey
    data
    text
    <p>This code works, but I just hacked it together with my limited knowledge of PHP and I'm sure there's a more elegant and efficient way to go about it. If you'd be so kind as to point out how I can improve, that would be great!</p> <p>So I have a CSV file, structured like so:</p> <pre><code>Code Class Value Status Date Created Date Redeemed ======================================================================== a51f3g45 gold 50 valid 2012-08-20 4f6a2984 silver 200 redeemed 2012-08-23 2012-08-27 gf3eb54b gold 150 valid 2012-08-30 etc... </code></pre> <p>The user fills out a form to change the <strong>Class</strong>, <strong>Value</strong>, and <strong>Status</strong> fields of a given line. I cobbled together the following code to replace the old values with the new ones:</p> <pre><code>$file = 'codes.csv'; $old_csv_string = file_get_contents($file); preg_match('/('.$_POST['code'].',.*,.*,.*,.*,.*)\n/',$old_csv_string,$matches); $old_row = $matches[1]; preg_match('/'.$_POST['code'].',(.*,.*,.*),.*,.*\n/',$old_csv_string,$matches_part); $old_row_part = $matches_part[1]; $new_row_part = $_POST['class'].",".$_POST['value'].",".$_POST['status']; $new_row = str_replace($old_row_part,$new_row_part,$old_row); $new_csv_string = str_replace($old_row,$new_row,$old_csv_string); file_put_contents($file,$new_csv_string); </code></pre> <p>So can I do better than 10 lines of code? Any advice would be greatly appreciated :)</p> <p><em>Note: I tried using <code>fgetcsv</code>, but I couldn't figure out how to find the unique code within a 2D array, then replace its siblings.</em></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload