user893970
user893970

Reputation: 899

changing the style inside "if" statement

I was trying to change the style of only a part of php. This is my codes;

if($fetch_array)
{
    $foto_destination = $fetch_array['foto'];
echo "<img src = '$foto_destination' height='150px' width='150px'>";
}
else
{



?>
<div style= "position:absolute; left:350px; top:70px;">
<?php
echo "<img src = 'images/avatar_default.png' height='150px' width='150px'>";
?>
</div>

But, this php part is inside if. This is why i could not change it? I want to display the image where i define it inside the div tag if the statement of "if" is true. How can i do this? Where am i missing? Thanks

Upvotes: 0

Views: 2478

Answers (4)

Clint C.
Clint C.

Reputation: 688

Did you mean like this?

<?php
if($fetch_array) {


    $photo = $fetch_array['foto'];
    $styles = 'position:absolute; left:350px; top:70px;';

} else {

    $photo = 'images/avatar_default.png';
    $styles = 'position:absolute; left:350px; top:70px;';

}
?>
<div style="<?php echo $styles; ?>">
<img src="<?php echo $photo; ?>" height="150" width="150" />
</div>

Upvotes: 1

Andreas
Andreas

Reputation: 2678

If I understand you correctly, it should be:

<?php

if($fetch_array){
?>
<div style= "position:absolute; left:350px; top:70px;">
<?php
    $foto_destination = $fetch_array['foto'];
    print "  <img src = '$foto_destination' height='150px' width='150px'>";
}else{
?>
<div style= "position:absolute; left:350px; top:70px;">
  <img src = 'images/avatar_default.png' height='150px' width='150px'>
<?php
}
?>

</div>

It shows the $foto_destination, if there is one.

HTH

Upvotes: 2

Michael
Michael

Reputation: 7374

Here's a more compact version, shorttags must be enabled.

<div style="position:absolute; left:350px; top:70px;">
  <img src="<?= isset($fetch_array['foto']) ? "images/avatar_default.png" : $foto_destination['foto'] ?>" height="150px" width="150px" />
</div>

otherwise:

<div style="position:absolute; left:350px; top:70px;">
  <img src="<?php echo isset($fetch_array['foto']) ? "images/avatar_default.png" : $foto_destination['foto'] ?>" height="150px" width="150px" />
</div>

Upvotes: 0

austinbv
austinbv

Reputation: 9491

That is correct or you can do an isset()

if (isset($fetch_array) {
  ...

The only advantage being that it will not error if the variable is undefined

Upvotes: 0

Related Questions