0

So I know this answer has been asked before, but after reading them I am still not understanding where my error is. From what I've gathered, I would throw this exception if I was referencing an element of the array that didn't exist, however, I am, and my code uses this to further execute. Does anyone know what is wrong with this code? I am getting undefined offset 1 - 16.

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

        $row = explode(",", $Users[$i]); 
        if ($row[$i] == $user){

            $userstring="$row[0]".","."$row[1]".","."$row[2]".","."active\n";

        }

    }

Edit to show user and users vars:

$user = $_GET['username'];
    $Users = file("../writeable/users.txt");
still2blue
  • 193
  • 1
  • 18
  • If you don't tell us what you don't understand, we can't help you. (Seems like you took much time to write your *answer*.) – Rizier123 Oct 18 '15 at 21:44
  • Well I think I did, I don't understand why I'm getting the undefined offset notice. It is coming from the `if` statement line. I am searching the array (a flat file) to see if the element contains the user I am looking for. What would cause it so throw that error? @Rizier123 – still2blue Oct 18 '15 at 21:50
  • See the dupe for a full answer. But do: `print_r($Users);` and you will see the structure of your array and you *try* to access key's which don't exists. – Rizier123 Oct 18 '15 at 21:51
  • But how? The `$i < count($Users)` should stop it before it gets to keys that do not exist right? I have read the dupe, and read it before I posted, and still am not understanding what I would have to change to fix the error from occuring. @Rizier123 – still2blue Oct 18 '15 at 21:55
  • You just `count()` the array and use a counter to access the array. But there is no need that your array is enumerated. (e.g. `0,1,2,3,`) it also can be associative. – Rizier123 Oct 18 '15 at 21:57
  • Ok, so are you saying I don't need the for loop at all? If not, and I initialize `$i = 0`, it checks one index and stops. Could you please elaborate on what I should do? @Rizier123 – still2blue Oct 18 '15 at 21:59
  • Use a `foreach` loop instead. And you maybe also want to `implode()` , `$row`. – Rizier123 Oct 18 '15 at 22:01
  • i almost always use foreach() when looping arrays. to really answer this question we need to see what `$Users` and `$user` looks liks –  Oct 18 '15 at 22:01
  • @Dagon I am new in php, so I do struggle with things in the language. I edited my original post to show what I have in those vars. `$Users` is just pointing to the text file where things are set up like `username,hashpass,email,status` and `$user` is just getting the username that was used to create the account – still2blue Oct 18 '15 at 22:07
  • 1
    @still2blue http://pastebin.com/JUW1Ad1z – Rizier123 Oct 18 '15 at 22:09
  • 1
    the problem is here: `if ($row[$i] == $user)`. `$i` is the index of the users array, not of the `$row` array. – tacone Oct 18 '15 at 22:14

0 Answers0