0

i normally use my online web-server for web development, but for some reasons i needed to test it in my XAMPP locally.

my code below will fetch images from a website via curl, and display the total images fetch.

what baffles me, im getting this error on XAMPP:

Notice: Undefined offset: 15 in C:\Web\xampp\htdocs\curl\fetch.php on line 69

line code 69: is if($images_array[$i]) { below

    <?php
    $image_regex = '/<img[^>]*'.'src=[\"|\'](.*)[\"|\']/Ui';
    preg_match_all($image_regex, $html, $img, PREG_PATTERN_ORDER);
    $images_array = $img[1];
    ?>

    <div class="images">

    <?php
    $k=1;
    for ($i=0;$i<=sizeof($images_array);$i++) {
        if($images_array[$i]) {
            if(strstr($images_array[$i],'http')) {
            echo "<img src='".$images_array[$i]."' width='100' id='".$k."' >";
            $k++;
            } 
        }
     }
     ?>

    <input type="hidden" name="total_images" id="total_images" value="<?php echo --$k?>" />

    </div>

i have no problems using this code in my online webserver. i imported all my files from my webserver to XAMPP with no changes made with it. also, my curl is enabled by checking phpinfo()

i hope someone could point whats making this undefined offset error.

2
  • check var_dump($images_array) or print_r($images_array) to see what is inside $images_array. Commented Nov 1, 2013 at 13:06
  • You probably don't have any problems using it on your local server either. Read the message, it's not an error, it's a notice. Just differences in the PHP's error_reporting value. Commented Nov 1, 2013 at 13:06

4 Answers 4

1

Don't use <= sizeof($array):

for ($i = 0; $i < sizeof($images_array); $i++) {

sizeof()/count() return the number of entries. Since array indices start with 0, you must either use $i <= count($arr) - 1 or use $i < count($arr).

Error reporting is probably turned off in your production environment, therefore you don't see the notice.

Sign up to request clarification or add additional context in comments.

Comments

0

Remove the <= from for ($i=0;$i<=sizeof($images_array);$i++)

Since $i is starting from 0

Comments

0

change <= in your for into just <

Because if the sizeof($images_array) is for example 5 , $images_array[5] will not exist.

Only 0 ... 4 (5 in total).

By changing <= in your for into <, you will prevent accessing $images_array[5] and thus prevent the notice from being shown.

Comments

0

Instead of the

if($images_array[$i]) {

use this:

if(isset($images_array[$i])) {

And also use this:

$i< sizeof($images_array) 

or $i < count($images_array)

instead of $i<=sizeof($images_array)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.