0

I have a text file called "product.txt" that includes some products:

Porsche Bike^A bike with a brand name!^10,000
Pretty Shoes^Come to our shoe store^54.45
Pie Fest!^Oh yeah this is officially the best pie ever^3.45
Inside Out Umbrella^Designer Umbrellas for low cost =^14.55
Coffee^Come get your morning dessert^4.59

I want to put them into an array with a function:

function loadFile() {
    $filename = ('product.txt');
    $file = fopen($filename, 'r');
    while (!feof($file)) {
        $line = trim(fgets($file));
        return $array = explode("^", $line);
    }
    fclose($file);
}

The problem with my function is that it won't put all of the products into the array, but only the first line!

2
  • 1
    You're returning inside the loop. That's why you only get the first line. Commented Feb 5, 2018 at 23:17
  • I don't know if this applies to your particular solution but something like php.net/manual/en/function.fgetcsv.php might be better than coding it yourself. Commented Feb 5, 2018 at 23:33

1 Answer 1

1

Change your function to

function loadFile() {
    $line = array();
    $filename = ('product.txt');
    $file = fopen($filename, 'r');
    while (!feof($file)) {
        $line[] = trim(fgets($file));
    }
    fclose($file);
    return $line;
}
Sign up to request clarification or add additional context in comments.

1 Comment

It seems like the OP wants to create a multidimensional array, so I guess it should be: $line[] = explode("^", trim(fgets($file)));

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.