user1295342
user1295342

Reputation: 43

PHP/Codeigniter - For Loop [Undefined offset]

for($i=0;$i<count($status);$i++)
{
    $conf = array(
        'source_image' => $status[$i]['full_path'],
        'new_image' => $this->upload_path . '/thumbs',
        'maintain_ratio' => true,
        'width' => 200,
        'height' => 200
    );

    $this->load->library('image_lib', $conf);
    $this->image_lib->resize();

    $this->image_lib->clear(); // complete reset    
    $this->image_lib->initialize($conf); // complete reset
}

            .

always keep missing the last thumbnail creation cycle. when trying for($i=0;$i<=count($status);$i++). i get this notice Undefined offset

Upvotes: 1

Views: 2578

Answers (2)

DaveRandom
DaveRandom

Reputation: 88677

By using a for loop you are assuming that the keys of the array are contiguous, which they may not be. You are also assuming that every second level array has a full_path key, which it may not. Use foreach instead, and do an isset() check on the full_path key:

foreach ($status as $item)
{

    if (!isset($item['full_path'])) continue;

    $conf = array(
        'source_image' => $item['full_path'],
        'new_image' => $this->upload_path . '/thumbs',
        'maintain_ratio' => true,
        'width' => 200,
        'height' => 200
    );

    $this->load->library('image_lib', $conf);
    $this->image_lib->resize();

    $this->image_lib->clear(); // complete reset    
    $this->image_lib->initialize($conf); // complete reset
}

Upvotes: 2

Taha Paksu
Taha Paksu

Reputation: 15616

try this:

$this->load->library('image_lib');
$stat = array_values($status);
for($i=0;$i<count($stat);$i++)
{
$conf = array(
    'source_image' => $stat[$i]['full_path'],
    'new_image' => $this->upload_path . '/thumbs',
    'maintain_ratio' => true,
    'width' => 200,
    'height' => 200
);

$this->image_lib->initialize($conf); // complete reset
$this->image_lib->resize();

}

Upvotes: 0

Related Questions