Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

PHP Help Needed with "Notice: Trying to Access Array Offset on Value of Type Null" Error

JimmysNetwork

Active Coder
Staff Team
Guardian
Hello,

I’m encountering the following error in my PHP game code I am working on currently:

Notice: Trying to access array offset on value of type null in /public_html/rpg/game.php on line 53

Here is the part of my code that seems to be causing the issue:

PHP:
// Handle POST requests (attacking NPC, etc.)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $data = json_decode(file_get_contents("php://input"), true);

    if ($data['action'] === 'attack') {
        // Randomly select an NPC from the map
        $npcId = array_rand($npcs);  // Random NPC selection by ID
        if (isset($npcs[$npcId])) {
            $npc = $npcs[$npcId];


I believe it’s related to how I'm trying to access $npcs[$npcId], but I’m not sure why it’s showing as null on line 53. The $npcs array is populated earlier, so I'm not sure why it would be null when I try to access it.

Any help would be greatly appreciated! I believe I am overthinking the solution.

Thanks!
 
Did you print out the log $npcs before you call array_rand($npcs)

Yeah here is my game.php code to make it easier;


PHP:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();
require_once 'includes/database.php';
require_once 'includes/functions.php';

// Load data from JSON files
$maps = loadJsonData('data/maps.json');
$npcs = loadJsonData('data/npcs.json');
$items = loadJsonData('data/items.json');
$drops = loadJsonData('data/drops.json');

var_dump($npcs);

// Check if the data was loaded correctly
if (!$maps || !is_array($maps)) {
    echo json_encode(["error" => "Maps data is not valid or empty"]);
    exit;
}
if (!$npcs || !is_array($npcs)) {
    echo json_encode(["error" => "NPCs data is not valid or empty"]);
    exit;
}
if (!$items || !is_array($items)) {
    echo json_encode(["error" => "Items data is not valid or empty"]);
    exit;
}
if (!$drops || !is_array($drops)) {
    echo json_encode(["error" => "Drops data is not valid or empty"]);
    exit;
}

// Check if the user is logged in and fetch their data
if (isset($_SESSION['user_id'])) {
    $userId = $_SESSION['user_id'];
    $user = getPlayerStatistics($userId);  // Fetch the player's stats

    // Ensure the user data is valid
    if (!$user) {
        echo json_encode(["error" => "User data not found"]);
        exit;
    }
} else {
    echo json_encode(["error" => "User not logged in"]);
    exit;
}


// Handle POST requests (attacking NPC, etc.)
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $data = json_decode(file_get_contents("php://input"), true);

    if ($data['action'] === 'attack') {
        // Randomly select an NPC from the map
        $npcId = array_rand($npcs);  // Random NPC selection by ID
        if (isset($npcs[$npcId])) {
            $npc = $npcs[$npcId];

            if ($npc) {
                // Battle logic: NPC attacks player, player attacks NPC
                $playerAttack = rand(5, 15); // Random attack range for player
                $npcAttack = $npc['attack'];

                // Deal damage to the NPC and the player
                $npc['health'] -= $playerAttack;
                $user['health'] -= $npcAttack;

                // Determine the result of the attack
                $playerWins = $npc['health'] <= 0;

                // Experience gain logic
                if ($playerWins) {
                    $user['experience'] += $npc['experience'];

                    // Check if the player leveled up
                    if ($user['experience'] >= calculateExperienceToNextLevel($user['level'])) {
                        $user['level']++;
                        $user['experience'] = 0; // Reset experience for next level
                    }

                    // Calculate TNL (To Next Level)
                    $experienceToNextLevel = calculateExperienceToNextLevel($user['level']);
                    $user['tnl'] = $experienceToNextLevel - $user['experience'];
                }

                // Save updated user data to the database
                saveUserData($userId, $user['health'], $user['level'], $user['experience'], $user['tnl']);

                // Prepare the action log
                $actionLog = [
                    'success' => $playerWins,
                    'playerHealth' => $user['health'],
                    'playerLevel' => $user['level'],
                    'playerExperience' => $user['experience'],
                    'playerTnl' => $user['tnl'],
                    'npcName' => $npc['name'],
                    'npcHealth' => $npc['health'],
                    'experienceGained' => $npc['experience'],
                    'npcAttack' => $npcAttack,
                    'playerAttack' => $playerAttack
                ];

                // Return response with updated stats and action log
                echo json_encode($actionLog);
                exit;
            }
        }
    }
}

?>
 
Update the condition to
PHP:
if (!empty($npcId) && !empty($npcs[$npcId])) {

By the way, without any var_dumps in the file etc, what code is showing on line 53 in your file because in the file that you posted line 53 is:
PHP:
$data = json_decode(file_get_contents("php://input"), true);

Edit to add:
What version of php are you running and on what OS?
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom