too long

I'm trying to echo a simple json_encoded file.

<?php
$allMessages = file_get_contents("chatmessages.txt");

$allMessagesArr = explode(PHP_EOL, $allMessages);
$newObj = [];
var_dump($allMessagesArr);
foreach ($allMessagesArr as $thisLine) {
    // echo($thisLine . "
");
    if (empty($thisLine) ) {

    } else {
        $thisLineArr = explode("|", $thisLine);

        $newObj[trim($thisLineArr[0])] = trim($thisLineArr[1]);
        // echo("here comes another one ".$thisLineArr[0] . " : ". $thisLineArr[1]."
");
    }
}
$newObjForFront = json_encode($newObj);
echo($newObjForFront);

chatmessages.txt looks like this

bob|hello
jimmy|second try incoming again
sam|third try

bob|oh damn

I've echoed each individual line within the loop and the fourth element appears. However, when I echo $newObjForFront, it's missing the last element. Any ideas why?

When you create your final array $newObj in

$newObj[trim($thisLineArr[0])] = trim($thisLineArr[1]);

Your using the name as the index to the array. As array indexes have to be unique, this means in fact the last entry overwrites the first one, so your actual output is...

{"bob":"oh damn","jimmy":"second try incoming again","sam":"third try"}

So it is in fact the first message that is missing.

Edit:

If you wanted to just have all of the messages, then you could store them using

$newObj[] = [ "user"=> trim($thisLineArr[0]), "msg" =>trim($thisLineArr[1])];

Which would give you the output as...

[{"user":"bob","msg":"hello"},{"user":"jimmy","msg":"second try incoming again"},{"user":"sam","msg":"third try"},{"user":"bob","msg":"oh damn"}]

$newObj[trim($thisLineArr[0])] = trim($thisLineArr[1]); this line will replace value with the last message of any username. if any username have multiple messages then only last message will be stored in the array.

By creating multidimensional you can store multiple messages with the same username. Check below code that may help you

$newObj[][trim($thisLineArr[0])] = trim($thisLineArr[1]);