I have a block of PHP code that looks like this:
$flag = false;
if (empty($links))
{
echo '<h1>You have no uploaded images</h1><br />';
}
foreach ($links as $link)
{
$extension = substr($link, -3);
$image_name = ($extension == 'peg') ? substr($link, -15) : substr($link, -14);
($delete_submit) ? deleteImage('.' . $image_name, $link) : '';
echo '<div>';
echo '<table>';
echo '<tr><td class="fullwidth"><a class="preview_img" href="' . $link . '"><img src="' . $link . '" title="Click to enlarge" width="300" class="thumb" /></a></td></tr>';
echo '<tr><td><span class="default">Direct:</span> ';
echo '<input type="text" readonly="readonly" class="link-area" onmouseover="this.select();" value="' . $link . '" />';
echo '</td></tr>';
echo ($flag) ? '<hr /><br>' : '';
echo '</table>';
echo '<br>';
echo '</div>';
$flag = true;
}
I want the <div> to include a different class based on if it is even or odd. If it is even, it gets X class, if it's odd it gets Y class.
How do I do this in my case? I'm totally clueless and I don't know how to start!
Initialise a variable $count=0; before the loop. Then place the following in the loop: ++$count%2?"odd":"even".
$count = 0;
foreach ($links as $link)
{
$extension = substr($link, -3);
$image_name = ($extension == 'peg') ? substr($link, -15) : substr($link, -14);
($delete_submit) ? deleteImage('.' . $image_name, $link) : '';
echo '<div class="' . (++$count%2 ? "odd" : "even") . '">';
[...]
$i++;
echo '<div class="'.($i%2 ? 'odd':'even').'>';
[...]
before the foreach, declare a boolean:
$div_flag = false;
in the foreach, where you echo the div add this:
"class=".( $div_flag ? "'odd'" : "'even'" )
at the end of the foreach (or anywhere in it, really) add this:
$div_flag = !$div_flag;
If you're working on a prototype site, you could always implement a pure CSS solution:
div:nth-child(even) { /* Apply even class rules here */ }
div:nth-child(odd) { /* Apply odd class rules here */ }
The reason I recommend that you only use this for prototype sites is because the compatibility for :nth-child does not support IE8 or below.
Try something like this
$count = 0;
foreach($links as link) {
$count++;
print ($count % 2 == 1) ? "odd" : "even";
}
If you are using a modern browser, you can use CSS with something like this in your style sheet.
div:nth-child(odd)
{
background:#ff0000;
}
div:nth-child(even)
{
background:#0000ff;
}
Add a variable for your loop.
$c = true;
foreach ($links as $link)
{
$extension = substr($link, -3);
$image_name = ($extension == 'peg') ? substr($link, -15) : substr($link, -14);
($delete_submit) ? deleteImage('.' . $image_name, $link) : '';
echo '<div'.(($c = !$c)?' class="odd"':'').">
//echo '<div>';
echo '<table>';
echo '<tr><td class="fullwidth"><a class="preview_img" href="' . $link . '"><img src="' . $link . '" title="Click to enlarge" width="300" class="thumb" /></a></td></tr>';
echo '<tr><td><span class="default">Direct:</span> ';
echo '<input type="text" readonly="readonly" class="link-area" onmouseover="this.select();" value="' . $link . '" />';
echo '</td></tr>';
echo ($flag) ? '<hr /><br>' : '';
echo '</table>';
echo '<br>';
echo '</div>';
$flag = true;
}
Without counters:
<?php $toggle_class = 'even';?>
<?php foreach ($links as $link):?>
<?php $toggle_class = ($toggle_class == 'odd' ? 'even' : 'odd');?>
<div class="<?php echo $toggle_class;?>">
Your div content...
</div>
<?php endforeach;?>
This is the easy tricks
function check_odd_even($data){
if($data % 2 == 0){
$data = "Even";
}
else{
$data = "Odd";
}
return $data;
}
if (check_odd_even($index) == 'Odd'){
//layout 1....
}else{
//layout 2....
}
Related
I have a foreach statement in my app that echos a list of my database results:
<?php
foreach($featured_projects as $fp) {
echo '<div class="result">';
echo $fp['project_name'];
echo '</div>';
}
?>
I would like to:
On every third result, give the div a different class. How can I achieve this?
You can use a counter and the modulo/modulus operator as per below:
<?php
// control variable
$counter = 0;
foreach($featured_projects as $fp) {
// reset the variable
$class = '';
// on every third result, set the variable value
if(++$counter % 3 === 0) {
$class = ' third';
}
// your code with the variable that holds the desirable CSS class name
echo '<div class="result' . $class . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
<?php
foreach ($featured_projects as $i => $fp) {
echo '<div class="result' . ($i % 3 === 0 ? ' third' : '') . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
If the $featured_projects array is based on incremental index you could simply use the index and the modulo % operator.
Otherwise you would have to add a counter.
http://php.net/manual/en/language.operators.arithmetic.php
add a counter in this loop and check if counter equals three and apply class.
Using a counter and modulo operator this is easy to implement
<?php
foreach($featured_projects as $fp) {
if(++$i % 3 === 0) {
$class = ' something';
} else {
$class = '';
}
echo '<div class="result' . $class . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
<?php
$i = 0;
foreach($featured_projects as $fp) {
echo '<div class="'.($i++%3 ? 'result' : 'other_class').'">';
echo $fp['project_name'];
echo '</div>';
}
?>
What leaves your code mostly in tact would be
<?php
$i = 1;
foreach($featured_projects as $fp) {
printf ('<div class="%s">',(($i % 3) ? "result" : "result_every_third" ));
echo $fp['project_name'];
echo '</div>';
$i++;
}
?>
But you may want to consider using a for or while construct around "each($featured_projects)" (see http://php.net/manual/en/function.each.php) which may result in neater code.
<?php
$counter = 0;
foreach ($featured_projects as $fp) {
echo '<div class="result' . ($counter++ % 3 === 0 ? ' third' : '') . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
You can add a counter in loop ...try the following...
<?php
$i = 0;
foreach($featured_projects as $fp) {
$i = ++$i;
if(($i%3) == 0)
{
$class1 = 'test1';
}
else
{
$class1 = 'test2';
}
echo '<div class="'.$class1.'">';
echo $fp['project_name'];
echo '</div>';
}
?>
This is the working version, sorry for my prev version:
<?php
$featured_projects[0]['project_name'] = "pippo";
$featured_projects[1]['project_name'] = "pippo2";
$featured_projects[2]['project_name'] = "pippo3";
$class[0] = "class1";
$class[1] = "class2";
$i=0;
foreach($featured_projects as $fp) {
$i++;
if ($i == 3) {
$c = $class[1];
$i=0;
} else {
$c = $class[0];
}
echo "<div class=\"$c\">";
echo $fp['project_name'];
echo "</div>\n";
}
?>
Produces:
<div class="class1">pippo</div>
<div class="class1">pippo2</div>
<div class="class2">pippo3</div>
if (isset($_GET['q'])){
$q = $_GET['q'];
//variables
$sql = "SELECT * FROM products WHERE product LIKE '%$q%' OR search LIKE '%$q%'";
$result = $conn->query($sql);
//check database
if($result->num_rows > 0){
while ($row = $result->fetch_array()){
$product = $row['product'];
$productImage = $row['product_image'];
$price = $row['price'];
$seller = $row['seller_name'];
$sellerImage = $row['seller_image'];
$desc = $row['description'];
$search = $row['search'];
$console = $row['console'];
$array = array($product, $price, $productImage);
$arrayDesc = array($desc, $sellerImage);
if (preg_match('/Game/', $seller)){
for ($num = 0; $num < 3; $num++) {
echo '<div class="tile col-md-4 col-sm-3">';
if($num == 0){
echo '<div class="tileTitleBox"><h4>' . $array[$num] . '</h4></div>';
}
if($num = 1){
echo '<p class="price">' . $array[$num] . '</p>';
}
if($num = 2){
echo '<img class="tilePic" src="' . $array[$num] . '"/>';
}
// if($num = 3){
// echo '<div class = "desc"><p>' . $array[$num] . '</p></div>';
// }
echo '</div>';
}//For Iteration Loop - TILE
for($count = 0; $count < 2; $count++){
echo '<div class="tile-description col-md-4 col-sm-3 hidden">';
if($count == 0){
echo '<div class="desc"><p>' . $arrayDesc[$count] . '</p></div>';
}
if($count == 1){
echo '<img class="sellerImg" src="' . $arrayDesc[$count] . '"/>';
}
echo '</div>';
}//end for loop - TILE-DESCRIPTION
So as you see above, I have one for loop which creates the "tile" and the second which is supposed to create the "tile-description". The first one works well to create a single div with the class of "tile" in which my remaining contents is loaded into the div. But in the second for loop the "desc" dev and the "sellerImg" div are separated. The loop needs to go through the array various times.
Shown Bellow:
You can see that the "Tile" div contains "tileTitleBox", "price", and "tilePic". But the "tile-description" which is hidden, is separated into two divs. As opposed to holding both elements inside the same div.
#sam-dufel rightly pointed out you're overwriting the iterator
if($num = 1){
But in fact you shouldn't use any loops here:
echo '<div class="tile col-md-4 col-sm-3">';
echo '<div class="tileTitleBox"><h4>' . $array[0] . '</h4></div>';
echo '<p class="price">' . $array[1] . '</p>';
echo '<img class="tilePic" src="' . $array[2] . '"/>';
echo '</div>';
echo '<div class="tile-description col-md-4 col-sm-3 hidden">';
echo '<div class="desc"><p>' . $arrayDesc[0] . '</p></div>';
echo '<img class="sellerImg" src="' . $arrayDesc[1] . '"/>';
echo '</div>';
I want a gallery of uploaded images, showing 4 images each tr.
There needs to be a loop somewhere but I can't get it to work.
It needs to add a tr automatically when there are 4 images in a tr.
<?php
$folder = 'uploads/';
$filetype = '*.*';
$files = glob($folder.$filetype);
$count = count($files);
$sortedArray = array();
for ($i = 0; $i < $count; $i++) {
$sortedArray[date ('YmdHis', filemtime($files[$i]))] = $files[$i];
}
krsort($sortedArray);
echo '<table>';
foreach ($sortedArray as &$filename) {
echo '<td align="center">';
echo '<a name="'.$filename.'" href="#'.$filename.'"><img src="'.$filename.'" /></a>';
echo 'Bestand naam: ' . substr($filename,strlen($folder),strpos($filename, '.')-strlen($folder));
echo '</td>';
}
echo '</table>';
?>
Let a counter, say $i run alongside your foreach loop that ticks up by one every time the loop ran. Check for "every fourth element" with if ($i % 4 ==0)
Use a counter in your loop. It should look like this :
echo '<table>';
$ctr = 0;
foreach ($sortedArray as &$filename) {
echo ($ctr % 4 == 0) ? "<tr>" : "";
echo '<td align="center">';
echo '<a name="'.$filename.'" href="#'.$filename.'"><img src="'.$filename.'" /></a>';
echo 'Bestand naam: ' . substr($filename,strlen($folder),strpos($filename, '.')-strlen($folder));
echo '</td>';
$ctr++;
echo ($ctr % 4 == 0) ? "</tr>" : "";
}
echo '</table>';
<?php
$folder = 'uploads/';
$filetype = '*.*';
$files = glob($folder . $filetype);
$count = count($files);
$sortedArray = array();
$i = 0;
krsort($sortedArray);
echo '<table><tr>';
foreach($sortedArray as & $filename)
{
echo '<td align="center">';
echo '<a name="' . $filename . '" href="#' . $filename . '"><img src="' . $filename . '"/> </a>';
echo 'Bestand naam: ' . substr($filename, strlen($folder) , strpos($filename, '.') - strlen($folder));
echo '</td>';
if ($i % 4 == 0)
{
echo '</tr><tr>';
}
$i++;
}
echo '</tr></table>';
?>
I have a pretty complicated script that doesn't fully work with MySQL, it does partially though. Let me try to explain...
The results of my page are purely image names from a specific folder, means I use this function to get my results:
function get_all_images($dir)
{
$dir = opendir($dir);
$dirArray = array();
while($entryName = readdir($dir))
{
if(($entryName != ".") && ($entryName != "..") && ($entryName != ".svn") && ($entryName != ".htaccess"))
{
$dirArray[] = $entryName;
}
}
closedir($dir);
(sizeof($dirArray)) ? arsort($dirArray) : '';
return (is_array($dirArray)) ? $dirArray : '';
}
This is how I basically get results in my page:
<?php
include('includes/header.php');
$images = get_all_images('i');
$url = str_replace('www.', '', generate_site_url());
$flag = false;
$count = 0;
if (empty($images))
{
echo '<h2>There are no uploaded images</h2><br>';
}
foreach ($images as $image)
{
$filename = $image_name = $image;
$image_link = $url . IMAGES_PATH . $filename;
$user_id = fetch_user_id($image_link);
$delete_link = (isset($_POST['delete_link'])) ? $_POST['delete_link'] : '';
$delete_image = (isset($_POST['delete_image'])) ? $_POST['delete_image'] : '';
if ($delete_admin_submit)
{
unlink('./t/' . $delete_image);
unlink('./t/big' . $delete_image);
adminDelete('./i/' . $delete_image, $delete_link);
header('Location: ' . $imgit_action);
exit();
}
echo '<div class="' . ($count++ % 2 ? "odd-color" : "even-color") . '">';
echo '<table>';
echo '<tr><td class="fullwidth"><a class="preview_img" href="' . $image_link . '"><img src="' . $image_link . '" title="Click to enlarge" width="300" class="thumb" /></a></td></tr>';
echo '<tr><td><span class="default">Direct link:</span> ';
echo '<input type="text" readonly="readonly" class="link-area" onmouseover="this.select();" value="' . $image_link . '" />';
echo '<form method="post" action="" onsubmit="return confirmSingleDeletion();" style="display: inline;"> ';
echo '<input type="submit" class="icon_delete" name="delete_link" value="' . $image_link . '" title="Delete this image" />';
echo '<input type="hidden" name="delete_image" value="' . $image_name . '" />';
echo '</form>';
echo '</td></tr>';
echo ($flag) ? '<hr /><br>' : '';
echo '</table>';
if (!empty($user_id))
{
echo '<br><strong class="normal">Uploader ID:</strong> ';
echo '<em class="normal">' . $user_id . '</em><br>';
}
echo '<br>';
$flag = true;
}
?>
<span class="button-sub">« Back to Index</span>
<?php echo '</div>'; ?>
<?php include('includes/footer_alt.php'); ?>
Now I have not ANY simple clue how to start breaking my results into pages. I'm working here with over 12000 results and it takes a lot for the page to load, I need help to break this big result into pages.
Anyone willing to help me? At least give me a clue how to start? I would be really grateful.
Thanks a lot for reading.
Consider your array as you collect up the file names but after you have sorted them:
$imgs = array(
0 => 'image1.jpg',
1 => 'image2.jpg',
2 => 'image3.jpg',
3 => 'image4.jpg',
4 => 'image5.jpg',
5 => 'image6.jpg',
6 => 'image7.jpg',
7 => 'image8.jpg',
);
// create some vars which you can use in your pagination
$perpage = 3 ;
$page=2;
$range_end = ($perpage*$page)-1;
$range_start = ($perpage*($page-1));
$display=range($range_start,$range_end);
// loop through results
foreach($display as $show){
echo $imgs[$show];
}
Does that get you a start?
Thanks for trying to answer me Cups and Umair Khan, but I found the working solution here:
http://tiffanybbrown.com/2008/12/14/simple-pagination-for-arrays-with-php-5/
I have a block of code thats working perfectly to pull data about different office locations.
What I would like to do is be able to make the last iteration of this loop change the div class to something else so I can apply a different set of css styles.
$fields = get_group('Offices');
foreach($fields as $field){
echo'<div class="oloc">';
if($locationVar==NULL || $locationVar!=$field['office-location'][1]) {
echo '<a name="' . strtolower(str_replace(' ', '-', $field['office-location'][1])) . '"></a><h3>' . $field['office-location'][1] . '</h3>';
$locationVar = $field['office-location'][1];
} else {
echo "<br />";
}
if($field['office-gm'][1]){
echo '<div class="gm"><img src="http://maps.googleapis.com/maps/api/staticmap?center=' . $field['office-gm'][1] . '&zoom=9&size=250x250&markers=color:blue|label:A|' . $field['office-gm'][1] . '&sensor=false"></div>';
}
if($field['office-name'][1]){
echo '<strong>' . $field['office-name'][1] . '</strong><br /><br />';
}
if($field['office-phone'][1]){
echo 'Phone: ' . $field['office-phone'][1] . '<br />';
}
if($field['office-fax'][1]){
echo 'Fax: ' . $field['office-fax'][1] . '<br />';
}
if($field['office-address'][1]){
echo '<br />Address:<br />' . strip_tags($field['office-address'][1], '<br><br />') . '<br />';
}
if($field['office-webpage'][1]){
echo 'Web: ' . 'Office Webpage<br />';
}
if($field['office-email'][1]){
echo 'Email: ' . 'Office Email<br />';
}
if($field['office-emp'][1]){
echo 'Jobs: ' . 'Employment Application<br />';
}
if($field['office-fb'][1]){
echo 'Facebook: ' . 'Facebook<br />';
}
if($field['office_office_twitter'][1]){
echo 'Twitter: ' . 'Twitter<br />';
}
echo '</div>';
}
For cases like these you can use a CachingIterator and the hasNext() method:
$fields = get_group('Offices');
$it = new CachingIterator(new ArrayIterator($fields));
foreach($it as $field)
{
...
if (!$it->hasNext()) echo 'Last:';
...
}
Put every echo in a var, this class definition in a other var. Then at the end of your foreach you check like so:
$i = 0;
foreach(...
if( $i == count($fields) ) { // change class }
Try this
$i = 0;
$total = count($fields);
$final = false;
foreach($fields as $field){
$i++;
$final = ($i + 1 == $total)? true : false;
if($final)
echo'<div class="NEW_CLASS">';
else
echo'<div class="oloc">';
....
}
First you should get the total count of the offices so that when you are on the last iteration, you can do something about it.
$fields = get_group('Offices');
$fields_count = count($fields);
$i = 0;
foreach ($fields as $field) {
$is_final = ++$i == $fields_count;
echo '<div class="oloc' . ($is_final ? ' oloc-final' : '') . '">';
[...]
}