thenashone thenashone - 7 months ago 13
PHP Question

PHP dealing with Invalid argument and expects parameter's

Good Evening, i am trying to teaching myself php, as i go and decided to try build something for our LAN server at work.

i have the following code that works and displays the images from a directory, i am using this as i am building a booking in system for work and naming the image by the job number.

for this i'm naming the images test but having a issue if there inst any images.

<?php

$directory = "saved_images/";


$images = glob("" . $directory . "test*.jpg");

$imgs = '';

foreach($images as $image){ $imgs[] = "$image"; }




$imgs = array_slice($imgs, 0, 20);

$result = count($imgs);


if ($result == 0)
{

$img="No Photos";
echo $img;

}
} else {
foreach ($imgs as $img) {
echo "<img src='$img' /> ";
}}
?>


the issue is, if there is not any photos i would like it to echo no photos instead of the following errors

array_slice() expects parameter 1 to be array,


refering to this line

$imgs = array_slice($imgs, 0, 20);


and

Invalid argument supplied for foreach()


refering to this line

foreach ($imgs as $img)


I have seen someone with a similar problem, but sadly they was advised to ignore the issue and turn off the error reporting, which didn't seem right, I am only asking as this inst causing any problem for the rest of the project and like to know how to fix this problem so if i encounter it again i know what to do.

Answer

All you need to do is set $imgs as an array (not a string), and check whether $imgs is empty or not. While you're at it, you will want to check if $images is empty or not, too.

$directory = "saved_images/";

$images = glob("" . $directory . "test*.jpg");

// since the entire script relies on $images not being empty,
// we should check for that to be sure before moving on
// you can also test for glob() returning FALSE on error, if you anticipate that it might
if ( ! empty($images) ) {

    $imgs = []; // this should be set as an array, not a string
    foreach ($images as $image)
    {
        $imgs[] = $image;
    }

    if ( empty($imgs) ) {
        echo 'No Photo';
    }
    else {
        $imgs = array_slice($imgs, 0, 20);

        $result = count($imgs);
        foreach ($imgs as $img)
        {
            echo "<img src='$img'> ";
        }
    }
}
else {
    echo 'No images in ' . $directory . ';
}