0

I am trying to call a function inside an array as a value but is not working the function instead is echoed outside the array.

Here is my code example:

function plm() {
    global $InfoPing;
    foreach($InfoPing['description']['extra'] as $plm) {
        echo $plm['text'];
    }
}

$json = array(
    'status' => 'Online',
    'motd' => array(
        'ingame' => plm()
    ),
    'host' => array(
        'host' => $host,
        'port' => $port
    ),
    'players' => array(
        'max' => $InfoPing['players']['max'],
        'online' => $InfoPing['players']['online']
    ),
    'version' => array(
        'version' => $version[1],
        'protocol' => $InfoPing['version']['protocol']
    ),
    'queryinfo' => array(
        'agreement' => 'Ping',
        'processed' => $Timer
    )
);

echo json_encode($json, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);

here are the results Any help highly is appreciated.

2 Answers 2

1

As Blake Ottinger points out in their answer, you need to return the data, not echo. But when you return, you exit the function and only the first value will be returned. If you want text from all elements of $InfoPing['description']['extra'], then build an array and return it:

function plm() {
    global $InfoPing;
    foreach($InfoPing['description']['extra'] as $plm) {
        $result[] = $plm['text'];
    }
    return $result;
}

However, instead of the function you can just extract all text with a built-in function and assign it to the array:

'ingame' => array_column($InfoPing['description']['extra'], 'text');
Sign up to request clarification or add additional context in comments.

Comments

1

Your issue stems from your usage of echo within the plm() function. Because it echoes instead of returning, it sends it to the browser ahead of the rest of the JSON, and then returns NULL, thereby inserting the NULL value into the array. Change it to return instead.

function plm() {
    global $InfoPing;
    foreach($InfoPing['description']['extra'] as $plm) {
        return $plm['text'];
    }
}

This should fix your issues.

1 Comment

I would question why they use a loop as return returns only the first one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.