Question

I have some PHP which will output a set of images.If I write it this way

    foreach( $data as $inform ) {
    {if (isset($inform['file1'])) {
            echo '<img src="'.$inform['file1'].'"><br><br>'; 
        }
    } 

It will display the 4 different images in the array $inform['file1'] with 2 line breaks in between each, but if I want to position them on the page like this

     foreach( $data as $inform ) {
       if ( isset( $inform['file1'] ) ) {
         echo '<div style="position:absolute; top:400px;"><img src="'.$inform['file1'].'"><br><br>
       </div>'; 
    }}

Then it displays all 4 images on top of each other, but in the right location.

I've tried styling it in css and nothing works. Can anybody help a newbie learn this?

Thanks in advance.

Was it helpful?

Solution 2

Your biggest problems here are:

  1. You haven't explained what you want to achieve, and
  2. You are mixing in PHP which is making a relatively simply problem seem harder to solve

The styling and positioning of elements should be managed through CSS (preferably not inline CSS).

Your PHP should be:

if( count( $data ) ){
  echo '<div class="file1_container">';
 # If there are elements in the $data array
  foreach( $data as $inform ){
    if( isset( $inform['file1'] ) ){
      echo '<img src="'.$inform['file1'].'" />'; 
    }
  }
  echo '</div>';
}else{
 # No elements in the $data array
}

Your CSS could then be something like:

.file1_container {
  position:absolute;
  left:0;top:400px;right:0;
  text-align:center;
}

This will position a DIV containing all the images at 400px from the origin, and the IMGs within it will be on the same horizontal line, aligned to the centre of the DIV.

OTHER TIPS

It's nothing to do with your foreach loop. You're literally telling the images to go on top of each other, so that's what they are doing. If you would like to add spacing to the top, put a container div around the images and do a margin-top: 400px;.

Your practice is bad, but if you must:

foreach($data as $inform){
  if(isset($inform['file1'])) {
    echo "<div><img src='{$inform['file1']}' /></div><br /><br />"; 
  }
}

Of course, this would add two breaks after the last one as well. You cannot have multiple items in different places using the same position:absolute, since they will all be relative to the last position:relative. Regardless, you should use CSS.

#PHP
foreach($data as $inform){
  if(isset($inform['file1'])) {.
    echo "<div class='someClass'><img src='{$inform['file1']}' /></div"; 
  }
}

/*CSS*/
.someClass{
  margin-top:10px;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top