0

The results are not fetched completely from NewsApi.I am new to PHP. Please help me get all list from NewsApi. Here is my code `

<?php
$urlsources=file_get_contents("https://newsapi.org/v1/sources");
$urlsourcearray = json_decode($urlsources,true);
$sources=$urlsourcearray['sources'];

for($i=0;$i<=count($sources);$i++){
  $sites = $urlsourcearray['sources'][$i];
  echo $sites['url'];
}

?>
Marc Delisle
  • 8,879
  • 3
  • 29
  • 29
Intra
  • 177
  • 1
  • 2
  • 7
  • Using `<=` will exceed the possible range of indices of an array (`[0 - (len - 1)]`). You should be using `$i < count($sources)`, first off. – Bytewave Nov 08 '17 at 16:13
  • You should declare `count($sources)` outside of the for loop, as a variable. Then use that variable in the loop `$i < $countOfSources`. If you use `count()` inside the loop as you currently are, you will be calling `count()` on every single iteration, which is inefficient. – GrumpyCrouton Nov 08 '17 at 16:22

2 Answers2

2

Try like this using < instead of <= because you started from index 0, Also don't use array length count inside for loop. It's a bad practice to use array length's count inside loops.

$urlsources=file_get_contents("https://newsapi.org/v1/sources");
$urlsourcearray = json_decode($urlsources,true);
$sources=$urlsourcearray['sources'];
$count = count($sources); //check out this line
for($i=0;$i<$count; $i++){
  $sites = $urlsourcearray['sources'][$i];
  echo $sites['url'];
}
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

Your for loop is <= when it should just be <.

for($i=0;$i < count($sources);$i++){
 $sites = $urlsourcearray['sources'][$i];
 echo $sites['url'];
}

Arrays are zero-indexed. So if you have an array has 4 items, the indexes would be 0,1,2 and 3.

0x6563
  • 1,032
  • 10
  • 17
  • You should declare `count($sources)` outside of the for loop, as a variable. Then use that variable in the loop `$i < $countOfSources`. If you use `count()` inside the loop as you currently are, you will be calling `count()` on every single iteration, which is inefficient. Consider if the array had 100 items in it, you would literally call the `count()` function 100 times by the time it finished, instead of just once if you declare it seperately. – GrumpyCrouton Nov 08 '17 at 16:22