Jump to content

[SOLVED] looping over array


muckv

Recommended Posts

I have some problems with displaying the contents of an array

 

<?php

$test= array();

$test=return_images();

for($i=-1;$i<count($test);$i++){
echo $test[$i]. '<br>';


}

 

Output = the First element in the array (B2.jpg)

 

print_r(return_images());

 

Give complete array

 

output = Array ( [2] => B2.jpg [3] => akso.gif [4] => sample.jpg )

 

 

Why does the array start at the third element?

Shouldn't it be Array ( [0] => B2.jpg [1] => akso.gif [2] => sample.jpg )

 

How to loop over it ?

 

Link to comment
Share on other sites

Well this is the function

 

function return_images()
{
    $images = array();

    $files = scandir('C:\wamp\www\IPTC\main\jan');

    for($i = 0;$i < sizeof($files);$i++) {
        $ext = substr($files[$i], strrpos($files[$i], '.') + 1);

        if ($ext == 'jpg' || $ext == 'jpeg' || $ext == 'gif') {
            $images[$i] = $files[$i];
        }
    }

    return $images;
}

Link to comment
Share on other sites

Well this is the function

 

function return_images()
{
    $images = array();

    $files = scandir('C:\wamp\www\IPTC\main\jan');

    for($i = 0;$i < sizeof($files);$i++) {
        $ext = substr($files[$i], strrpos($files[$i], '.') + 1);

        if ($ext == 'jpg' || $ext == 'jpeg' || $ext == 'gif') {
            $images[$i] = $files[$i];
        }
    }

    return $images;
}

that's because of your if{} statement inside the for loop. You only check for jpg|jpeg|gif but what about the rest? If the file is not jpg or jpeg or gif, the counter $i will get incremented as well, that's why your array index doesn't start at 1( or 0) but at 2.

 

Link to comment
Share on other sites

I've already answered the question, I believe. Removing $i will eliminate the count, since using [] will start at 0 and count up.

 

Change this:

 

$images[$i] = $files[$i];

 

To this:

 

$images[] = $files[$i];

 

By defining $i in the square brackets you are giving it a key. If you provide nothing then it will start at 0 and count its way up.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.