Hello! The goal is to produce a random phrase on the page from the array and count how many times it was displayed on the screen. To store the number of repetitions, I decided to use a number that is stored in an array with this phrase. And if the random number matches the key, take this variable, increment by one and put it back. The problem is that the number in the array is overwritten only once, and then again equal to the initial value. I understand that the array is reinitialized with the original values. Is this true and how can I fix it to work? Code below:

<?php $phrases = array( 1 => array ('phrase' => 'И один в поле воин!', 'number' => 0, ), 2 => array ('phrase' => 'Под лежачий камень вода не течет.', 'number' => 0, ), ); $from = 1; $to = count($phrases); $rand = rand($from, $to); foreach ($phrases as $key => $value) { if ($rand == $key){ $i = $phrases[$key]["number"]; $i++; $phrases[$key]["number"] = $i; echo $value["phrase"]." повторялось ".$phrases[$key]["number"]." раз"; } } ?> 

    1 answer 1

    The fact is that you put the array in the memory of the script and the lifetime of the array is determined only by the time of the script. In order to preserve the value, you need some kind of persistent storage: a file, a database, a NoSQL solution that will store information permanently.

    The simplest option is to store the array values ​​and view counters in a user session in the $ _SESSION array. However, it should be borne in mind that this data set will be individual for each of the users and reset to zero when initializing a new session.

    • Yes, I understood, I will make a DB. Thanks for the answer. - exStas