Jack Stefansky Jack Stefansky - 1 month ago 8
PHP Question

PHP inserts null at end of string

I've been writing simple api for my website and when function displays string it appends with null at the end of

<?php
//error_reporting(0);

class EnterData {

function addPlayedGames ($games) {
echo $games;
}

}

switch ($_GET['method']) {
case 'say':
$response = 'Hello';
break;
case '':
$response = 'No method has been called';
break;
case 'addToPlayCount':
$enter_data = new EnterData();
$response = $enter_data->addPlayedGames($_GET['games']);
break;

default:
$response = 'Unknown method | Error 01';
break;
}


if(!isset($_GET['method'])){
$response = 'Nothing has been passed.';
}

@header('Content-Type: application/json; charset=utf8');
echo json_encode($response);

?>


E.g.


examle.com/api.php?method=addToPlayCount&games=31293123


displays


31293123null

Answer Source

This function doesn't return anything.

function addPlayedGames ($games) {
    echo $games;
}

Functions that don't explicitly return anything will implicitly return null.

So when you use it:

$response = $enter_data->addPlayedGames($_GET['games']);

$response is set to null, and json_encode(null) returns the string "null".