Chris Burton
Chris Burton

Reputation: 1205

Simplify this PHP?

I was copy/pasting some PHP to get the outcome I wanted but I believe this could be simplified in a much better way. Could any developers help a designer out?

<?php
$url = dirname(__FILE__);
$id = substr( $url, strrpos( $url, '/' )+1 );
echo '<img src="../i/';
echo $id;
echo '.png" alt="';
echo $id;
echo '" />'; 
?>

Result: <img src="(name of $id)" alt="(name of $id)" />

Upvotes: 0

Views: 77

Answers (5)

CrimsonDiego
CrimsonDiego

Reputation: 3616

$url = dirname(__FILE__);
$id = substr( $url, strrpos( $url, '/' )+1 );
echo "<img src=\"../i/$id.png\" alt=\"$id\" />"

Upvotes: 0

Tiago Peczenyj
Tiago Peczenyj

Reputation: 4623

like this:

<?php
$url = dirname(__FILE__);
$id = substr( $url, strrpos( $url, '/' )+1 ); ?>

<img src="../i/<?php echo $id >.png" alt="<?php echo $id >" />

Upvotes: 0

rjz
rjz

Reputation: 16510

Here's a recycleable version:

function img_tag () {
  $url = dirname(__FILE__);
  $id = substr( $url, strrpos( $url, '/' )+1 );
  return "<img src=\"../i/$id.png\" alt=\"$id\" />";
}

elsewhere in your document, call this function as follows:

<?php echo img_tag(); ?>

Upvotes: 0

John Conde
John Conde

Reputation: 219804

<img src="../i/<?php echo $id; ?>.png" alt="<?php echo $id ?>">

Upvotes: 1

icktoofay
icktoofay

Reputation: 128991

You can use PHP's string interpolation for that:

echo "<img src=\"../i/$id.png\" alt=\"$id\" />";

Upvotes: 5

Related Questions