I’m getting a Notice: Undefined offset: 1 error when trying to display Twitch channel information on my site. The script is supposed to pull channel names from my database and then fetch their stream details from the Twitch API.
Here’s my code with the problematic section highlighted:
This offset error happens because you’re assuming the API response matches your channels array structure - it doesn’t. When channels are offline or don’t exist, the API returns fewer results or orders them differently. I’ve hit this same issue with streaming APIs. The problem is $streamData[$index] doesn’t match $channelsArray[$index] - the API response structure won’t align with your input array indexes. Loop through the actual $streamData array instead of using your channels array indexes. Add error checking too - use isset($streamData[$index]) before accessing nested properties to avoid those undefined offset notices. Also, that justin.tv API is ancient - Twitch killed it years ago. You should switch to the current Twitch API which has way better docs and more reliable responses.
Your array indexing won’t work because you’re assuming the API returns streams in the same order as your input channels - it doesn’t. Twitch might return them differently or skip offline channels completely, so your indices get mismatched. I hit this same problem building a stream aggregator. Fix it by looping through the actual API response instead of using your original channel array as the index. Also, wrap those nested array accesses in checks first: if(isset($streamData[$index]['channel']['channel_url'])) before trying to grab those properties. Bigger problem though - you’re using the old justin.tv endpoint that died in 2014. You’ll need to switch to the current Twitch Helix API with proper OAuth if you want this to actually work.
that’s a classic array mismatch. you’re assuming the API results match your input order, but twitch never works that way. the API might return 3 streams when you requested 5 channels, so $streamData[4] doesn’t exist.
don’t use $index from your channels array. loop directly through $streamData instead. and throw in some basic checks like if(!empty($streamData)) before the loop - otherwise you’ll get more errors when the API craps out.