What is wrong with this piece of code? html + php

I have a simple function that has two parameters: one for the image URL and the other for image attributes

function image_found($url,$attributes) { if(@getimagesize($url)) { echo '<img src="'.$url.'" '.$attributes.'/>'; } else { echo '<img src="'.base_url().'/site_images/image_not_found.svg" '.$attributes.'/>'; } } 

now what I'm trying to do is create a clickable image, if the image is found, now it's html code

 echo '<div class="panel-body">'; echo '<div class="col-md-12 col-lg-12 col-sm-12 text-center">'; $url = base_url().'product_images/'.$result->product_image.'.'.$result->image_type; $attributes = 'height="200px" width="100%"'; echo '<a href="product.com/full/url">'.image_found($url,$attributes).'</a>'; echo '</div>'; echo '</div>'; 

and this is the result that I get

 <div class="panel-body"> <div class="col-md-12 col-lg-12 col-sm-12 text-center"> <img src="http://localhost/nsc/product_images/7908076366784972032090.jpg" height="200px" width="100%"/> <a href="#"></a> </div> </div> 

I do not know what is wrong here, I use bootstrap

+6
source share
3 answers

Just use return statements instead of echo in your function, and your problem should be solved; -)

+1
source

When you need to return a value from a function, use the return instead of echo

When echo used, the result is immediately printed, and does not return to the place where the function is called. Here is an illustration.

 function printer(){ echo 'second'; } echo 'first'.' '.printer().' '.'last'; 

Output:

 secondfirst last 

This is the same as your code. The echo in image_found() is printed as

 <img src="http://localhost/nsc/product_images/7908076366784972032090.jpg" height="200px" width="100%"/> 

The rest of the echo command prints as

 <a href="#"></a> 

Therefore, using the return statement should solve your problem

0
source

The best way to check if your image exists (delete @) and then return (instead of echo):

 ... if(file_exists('your/path/to/image')) return '<img src="'.$url.'" '.$attributes.'/>'; else return '<img src="'.base_url().'/site_images/image_not_found.svg" '.$attributes.'/>' ... 
0
source

Source: https://habr.com/ru/post/985783/


All Articles