Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP adding the value 1 to a position in an array

I have a "what character are you" quiz website that is built in PHP for an assignment. I also need to store how many people get each of the 5 possible characters.

I have a text file with just the text - 0 0 0 0 0 Each 0 is a counter for the amount of times someone picks a specific character.

I explode it into an array

$txt = "results2.txt";
$scores = file_get_contents($txt);
$editablescores = explode(",", $scores);

Then depending on the score someone receives I want to add +1 to the appropriate 0 in the array.

This is an example of what I am using but it doesn't work. The following error comes up. Notice: Undefined offset: 4 in /Users/sinclaa3/Sites/PHPStyles/hi.php on line 53

0 0 0 0 0 is displayed but then 1 is added on to that as such. 0 0 0 0 0 1

if ($score < 6 ) {

$editablescores[0]++;
    //0 denotes the position in the array that I want to add one to

};



$storablescores = implode(",", $editablescores);
file_put_contents($txt, $storablescores);
like image 395
user3195675 Avatar asked Feb 20 '26 01:02

user3195675


1 Answers

Your explode is wrong; you say you have 0 0 0 0 0, then you try to explode on ,. Fixed:

$editablescores = explode(" ", $scores);

Note that your implode is wrong for the same reason; it should be:

$storablescores = implode(" ", $editablescores);
like image 136
elixenide Avatar answered Feb 21 '26 14:02

elixenide