2

I am new to PHP and I can't figure how function return array, I have two similar arrays, one hand defined and one return by a function but the first doesn't work after whereas the first does...

Here is my code :

<?php
function fileContent($file) {
    if(file_exists($file)){
        $arr = file($file) ;
        return($arr);
    }
    else{
        echo "This file doesn't exist";
    }
}
$values=fileContent("Ressources/myfile.txt");
print_r($values);
?>

<?php
$values= Array("Val1","Val2","Val3");
print_r($values);
?>

myfile.txt :

Val1
Val2
Val3

Both print_r show the same but then when I try to use the array with the one from the function, I can't do anything...

Wargal
  • 103
  • 1
  • 9
  • Your fileContent function returns a string, not an array. If you want it to return an array, you need to read the file line by line. Have a look at this: https://stackoverflow.com/questions/13246597/how-to-read-a-large-file-line-by-line – Sorix Sep 13 '19 at 08:34
  • 1
    @Sorix That's what the `file()` function does. Each line of the file becomes an array element. You're thinking of `file_get_contents()`. – Barmar Sep 13 '19 at 08:38
  • 1
    What do you mean by "I can't do anything"? You used it in `print_r()`, you should be able to use it in any other way. – Barmar Sep 13 '19 at 08:39
  • 1
    Post the code that's not working. – Barmar Sep 13 '19 at 08:39
  • Have you spelt the file path correctly? Ressources/myfile.txt – suspectus Sep 13 '19 at 08:39
  • 2
    @suspectus The question says that `print_r()` shows the correct results. – Barmar Sep 13 '19 at 08:40
  • `$values` is being overwritten: `$values= Array("Val1","Val2","Val3");` - is that the problem? – suspectus Sep 13 '19 at 08:45
  • @Sorix my $values are arrays, thats what i dont get, using `count`, `gettype`, and checking equality of each value is ok. But when I test equality of the two array, they doesn't match and `array_diff` give me `Array ( [0] => Val1 [1] => Val2 )` – Wargal Sep 13 '19 at 09:20
  • I find the problem, just file() putting space after each value, I don't know why it does that... – Wargal Sep 13 '19 at 09:32

1 Answers1

0

I finally found what was wrong. I hadn't notice that when you call file(), each element have a space just after it so when I was making a URL request, it had space in it Thanks all, I was just blind.

Wargal
  • 103
  • 1
  • 9
  • Why would `file()` add a space to every element? – brombeer Sep 13 '19 at 09:44
  • I don't have a clue... each array element is ending by a space and i doubled checked there is no space in my txt file. It may be the line break ? – Wargal Sep 13 '19 at 09:46
  • I'll try to play with the flags on a spare project to see how it really works maybe it can avoid some space or errors – Wargal Sep 13 '19 at 10:00