Encountering an index out of bounds issue while retrieving Twitch stream information

Issue with Index Out of Bounds When Fetching Data from Twitch API

I’m currently developing a PHP script that retrieves streaming information from Twitch, utilizing a list of channels saved in my database. The code is functioning to some extent, but I’m encountering this issue:

Notice: Undefined offset: 1

This error appears to arise when I iterate through the responses received from the API. Below is a snippet of my code:

<?php
// Guard against unauthorized access
if (!defined('_JEXEC')) {
    die('Unauthorized access');
}

$channelList = $params->get('channels');
$channelsArray = explode(',', $channelList);
$apiUrl = "https://api.twitch.tv/streams/?channel=";
$activeStreams = array();

// Construct the URL for API request
foreach($channelsArray as $key => $channel){
    if($key > 0) {
        $apiUrl .= ",";
    }
    $apiUrl .= $channel;
}

// Retrieve data from Twitch API
$response = file_get_contents($apiUrl);
$streamData = json_decode($response, true);

// Process each channel - ERROR OCCURS HERE
foreach($channelsArray as $index => $channelName){
    $channelUrl = $streamData[$index]['channel']['url'];
    $urlParts = explode('/', $channelUrl);
    $username = end($urlParts);
    $streamTitle = $streamData[$index]['status'];
    $currentGame = $streamData[$index]['game'];
    $viewerCount = $streamData[$index]['viewers'];
    
    displayStreamInfo($username, $viewerCount, $streamTitle, $currentGame);
    $activeStreams[] = checkStatus($username);
}

function displayStreamInfo($streamer, $viewers, $title, $game) {
    $gameIcon = ($game == "CS:GO") ? "csgo_icon.png" : "live.png";
    
    if ($streamer != null) {
        echo '<img src="./images/'.$gameIcon.'">';
        echo '<a href="https://twitch.tv/'.$streamer.'" target="_blank">';
        echo '<strong>'.$streamer.'</strong></a>';
        echo ' ('.$viewers.' viewers) - '.$title.'<br>';
    }
}

function checkStatus($user) {
    return ($user != null) ? $user : null;
}
?>

I think the problem might lie in how I’m accessing indices within the arrays, but I’m not sure what the root cause is. Has anyone faced similar situations while working with API data? Any insights or recommendations would be appreciated.

You’re assuming the channels array indices match the API response indices, but that’s not guaranteed. Twitch API doesn’t return streams in the order you requested them, and some channels might not be streaming at all - so you’ll get fewer results than channels you asked for. I hit this same issue with Twitch API last year. Fixed it by ditching index-based iteration for key-based lookup. Don’t use $streamData[$index] - instead, loop through the actual $streamData['streams'] array and match channels by name. The API response usually has a ‘streams’ key with the stream objects. Also, check that $streamData has the structure you expect before processing it. Handle cases where channels aren’t live. This’ll stop those undefined offset errors.

Your code assumes each channel in your list matches up with the API response by position - that’s the problem. The Twitch API only sends back data for channels that are actually live right now. So if you check 5 channels but only 3 are streaming, you get 3 results, not 5. When your loop tries to access positions 3 or 4, there’s nothing there. I’ve run into this same issue building stream monitors. Here’s what works: don’t loop through your channel list expecting matching positions. Instead, loop through the API response and match it against your channels. And always dump the response first with var_dump($streamData) to see what you’re actually getting - API formats change.

The issue is you’re treating the API response like it matches your input array structure, but Twitch’s API returns a different format. Check what’s actually in $streamData - you probably need $streamData['streams'][$index] instead of $streamData[$index]. Also throw in some isset($streamData[$index]) checks before accessing array elements to stop those notices.