0

I'm trying to show images from some directory using foreach.. But the problem is it's showing results in array, so if i want to print out first image I have to use $imag['0']..

Is there any way that I can bypass this number in this brackets?

Here's my code...

<?php
$domena = $_SERVER['HTTP_HOST'];
$galerija = $_POST['naziv'];
$galerija = mysql_real_escape_string($galerija);

define('IMAGEPATH', 'galleries/'.$galerija.'/');

foreach(glob(IMAGEPATH.'*') as $filename){
    $imag[] =  basename($filename);
?>
<img src="http://<?php echo $domena; ?>/galerija/galleries/<?php echo $galerija; ?>/<?php echo $imag['0']; ?>">
2
  • on the line $imag[] = basename($filename); why don't you just use $imag instead? so you dont need to use $img[0] afterwards.. Commented Nov 18, 2013 at 14:28
  • 1
    Your code does not really make any sense. You store all images into array and then echo just the first image. Why are you storing the images into array in the first place? Just echo them from the foreach loop. Also, if you only need the first one you should break; the loop after the first cycle.. you are wasting CPU cycles. Commented Nov 18, 2013 at 14:28

2 Answers 2

1

If you only need the first filename, then you could avoid the loop and directly access the first element of the array and use it afterwards:

$files = glob(IMAGEPATH.'*');
$filename =  array_shift(array_values($files));
$image = basename($filename);

And to display it, you could use sprintf():

echo sprintf('<img src="http://%s/galerija/galleries/%s/%s"/>', 
    $domena, $galerija, $image);
Sign up to request clarification or add additional context in comments.

Comments

0

Well you could first not create the array in the foreach statement and instead just print the img:

echo '<img src="', $domena ,'/galerija/galleries/', $galerija ,'/', $filename,'">';

Or you could iterate the array.

foreach($imag as $img): ?>
    <img src="http://<?php echo $domena; ?>/galerija/galleries/<?php echo $galerija; ?>/<?php echo $img ?>">
<?php endforeach; ?>

1 Comment

using $filename directly will break since he is passing it through basename()

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.