How do I assign unique static strings to a variable in a for loop? I'm trying assign a unique description and alt tag to a list of thumbnails. I have managed to get the loop to produce the thumbnails but I cannot work out how to assign unique values to each one based on the condition of the value. This is the for loop:
<?php
for ( $project=1; $project<=40; $project++ ) {
echo "
<a href=\"#\" class=\"thumb\">
<img src=\"images/thumbs/$project.jpg\" width=\"300\" height=\"140\" alt=\"$projectname\" title=\"$projectname\" />
<span class=\"client\">$projectname</span><span class=\"description\">$type</span>
</a>
";
}
?>
I tried this before the for loop but didn't work...
if ( $project = 1 ) {
$projectname = "client1";
$type = "Interactive Brochure Design";
}
else if ( $project = 2 ) {
$projectname = "client2";
$type = "Site Design";
}
if ( $project == 1 ) {
$projectname = "client1";
$type = "Interactive Brochure Design";
}
else if ( $project == 2 ) {
$projectname = "client2";
$type = "Site Design";
}
=
sets a variable and doesnt compare. ==
compares
of course there are probably more elegant ways for your project...
That's what arrays are there for. Something like:
$projects = array(
array('name' => 'client1', 'type' => 'Interactive Brochure Design'),
array('name' => 'client2', 'type' => 'Site Design'),
);
for ($n=0; $n<count($projects); ) {
$projectname = $projects[$n]['name'];
$type = $projects[$n]['type'];
$project = ++$n;
echo "
<a href=\"#\" class=\"thumb\">
<img src=\"images/thumbs/$project.jpg\" width=\"300\" height=\"140\" alt=\"$projectname\" title=\"$projectname\" />
<span class=\"client\">$projectname</span><span class=\"description\">$type</span>
</a>
";
}
Or you could also use foreach
:
foreach ($projects as $project) {
echo '<div>name: ' . $project['name'] . '</div>
<div>type: ' . $project['type'] . '</div>';
}
See it on codepad
You would usually begin with storing each project in an array, so you can easily loop through them. The values stored in the array could be objects of some "project" class, or an associative array, like this:
$projects = array(
array(
'name' => 'client1',
'type' => 'Interactive Brochure Design',
'filename' => 'client1.jpg',
),
array(
'name' => 'client2',
'type' => 'Site Design',
'filename' => 'client2.jpg',
),
);
foreach($projects as $project)
echo '
<a href="#" class="thumb">
<img src="images/thumbs/'.$project['filename'].'" width="300" height="140" alt="'.$project['name'].'" title="'.$project['name'].'" />
<span class="client">'.$project['name'].'</span><span class="description">'.$project['type'].'</span>
</a>
';