Hello everyone, there is such code:

<?php $poisk = 229786213; $row = file('fren.txt'); foreach ($row as $key => $value) { $baza = json_decode(file_get_contents("https://api.vk.com/method/friends.get?user_id=".$value."&access_token=0$token&v=5.80")); if(isset($baza->response->items)){ $array = $baza ->response->items; $key = array_search($poisk, $array); // $key = 2; if($key != FALSE){ $fp = fopen("counter.txt", "a+"); $mytext = "$value \r\n"; $test = fwrite($fp, $mytext); fclose($fp); echo "Good"; } } } ?> 

How to make so that foreach retained all values, and not just the last?

    2 answers 2

    I see several problem areas. 1) In a row (that is, in fren.txt) there can be one entry. Make echo $ row 2) The contents of $ baza> response-> items are not set, except once. 3) array_search constantly returns FALSE, except once.

    Your solution, other things being equal, should also work, but still it is better to open / close the file after the loop.

     $filename = "counter.txt"; $fp = fopen($filename, "a+"); if( $fp ) { foreach ($row as $key => $value) { //... $test = fwrite($fp, $mytext); //... } else { echo "Не могу открыть файл"; } fclose($fp); } 
    • Alas, it also does not save everything. - Ilona Kulyakova
    • Edited the answer - Alexander Chernin
    • I have a full path. And the problem here is not in opening / closing the file. And that foreach by default stores only the last value. And the fact that I will postpone the opening of the file will not help me. - Ilona Kulyakova
    • I edited the answer - Alexander Chernin

    Damn, code "tear your eyes." PHP7 in the yard and you write like in the last century. I will give an example as I wrote:

     foreach ($row as $key => $value) { $baza = json_decode(file_get_contents("https://..."),true); # Возвращает массив а не объект if( !@array_search($poisk, $baza['response']['items']) ) continue; # Пропускаем шаг цикла если ничего не найдено file_put_contents("counter.txt", "$value \r\n", FILE_APPEND); # Дописываем в конец файла echo "Good"; }