3

I have a file (Test.txt) with the following data: 1,0

I am wanting to read the contents of this file into an array and then print the variables. Here is my current code:

    function readUserDetails($username) {
    $userDetails = explode(',', file($username.".txt"));
    print($userDetails[0].$userDetails[1]);
}

If I call the readUserDetails function with the folowing parameters: "Test", I get the following errors:

Notice: Array to string conversion in C:\Users\s13\Game\Game6\default.php on line 128 Notice: Undefined offset: 1 in C:\Users\s13\Game\Game6\default.php on line 129 Array

Can I please have some help to get this working?

4 Answers 4

3

The PHP file() function reads a file into an array, one line of the file into each array element. See http://php.net/manual/en/function.file.php. explode() expects a string. Look at what file() is reading to see if it's what you want:

<?php
   ...
   $userDetails = file($username.".txt");
   print_r($userDetails);
?>
Sign up to request clarification or add additional context in comments.

Comments

2

file($username.".txt") already returns you an array and you are trying to explode an array with , delimeter

Try this

function readUserDetails($username) {
  $userDetails = explode(',', file_get_contents($username.".txt"));
  print($userDetails[0].$userDetails[1]);
}

Comments

0

You can use file_get_contents() to return the contents of a file as a string.

$userDetails = explode(',', file_get_contents($username.".txt"));

Comments

0

Try:

$array = explode( "\n", file_get_contents( $username .'txt' ) );

Comments

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.