How to count each field in php - php

I have the below code:
function cat_fields($fields)
{
global $cfg;
$fields['cat_furl'] = str_replace('%cat_safename%', $fields['cat_safename'], $cfg->getVar('urlformat_cat'));
$fields['cat_furl'] = $cfg->getVar('site_url') . str_replace('{cat_safename}', $fields['cat_safename'], $fields['cat_furl']);
$fields['cat_flink'] = '<a id="a' . count($fields) . '" href="' . $fields['cat_furl'] . '" title="' . $fields['cat_title'] . '">' . $fields['cat_name'] . '</a>';
return $fields;
}
And i am trying to count each field of $fields['cat_flink'] = '<a id="a' . count($fields) . '" I tried with id="a' . count($fields) . '" but it's returning the total number of field instead of counting them. How can i count them EACH.
Should be
<a id="a1"....>
<a id="a2"....>
Instead it's echoing me
<a id="15"....>
<a id="15"....>
..... and so on
Please help me on this matter.

You're trying to count all the fields in your array; Quoted from the PHP Manual:
Counts all elements in an array, or something in an object.
To get indices (i.e. the numbers you're looking for), you will have to set a starting number and loop over all your fields until you've got them all, and increment that number everytime your walk through the loop.
Your method however, seems to be for only one iteration, which means you would have to store your number elsewhere. A good way to do this would be adding the number as a parameter to your function:
function cat_fields($fields, $number)
{
global $cfg;
$fields['cat_furl'] = str_replace('%cat_safename%', $fields['cat_safename'], $cfg->getVar('urlformat_cat'));
$fields['cat_furl'] = $cfg->getVar('site_url') . str_replace('{cat_safename}', $fields['cat_safename'], $fields['cat_furl']);
$fields['cat_flink'] = '<a id="a' . $number . '" href="' . $fields['cat_furl'] . '" title="' . $fields['cat_title'] . '">' . $fields['cat_name'] . '</a>';
return $fields;
}
Having done that you should edit the loop (I presume) you're using to call the function multiple times:
for ($i = 1; $i < count($yourArray); $i++) {
// code
$foo = cat_fields($yourArray, $i);
// more code
}
Hope that helps.
EDIT:
I've edited the pastebin from lines 131-141:
if(($rs = $db->execute($sql)) && (!$rs->EOF))
{
$i = 1;
while(!$rs->EOF)
{
$rs->fields = seoscripts_prepare_cat_fields($rs->fields, $i);
$tpl->assign_array_d('tool_category_row', $rs->fields);
$tpl->parse_d('tool_category_row');
$rs->MoveNext();
$i += 1;
}
}

Counting like thatcount($fields) returns the numbers of fields you have you need to add a integer like i=0;
and increase it i++;

Try this
function cat_fields($fields)
{
global $cfg;
$fields['cat_furl'] = str_replace('%cat_safename%', $fields['cat_safename'], $cfg->getVar('urlformat_cat'));
$fields['cat_furl'] = $cfg->getVar('site_url') . str_replace('{cat_safename}', $fields['cat_safename'], $fields['cat_furl']);
$i=0;
foreach($fields as $field)
{
$fields['cat_flink'] = '<a id="a'.$i.'" href="' . $field['cat_furl'] . '" title="' . $field['cat_title'] . '">' . $field['cat_name'] . '</a>';
i++;
}
return $fields;
}

Try this
function cat_fields($fields)
{
global $cfg;
$fields['cat_furl'] = str_replace('%cat_safename%', $fields['cat_safename'], $cfg->getVar('urlformat_cat'));
$fields['cat_furl'] = $cfg->getVar('site_url') . str_replace('{cat_safename}', $fields['cat_safename'], $fields['cat_furl']);
$str = '';
$i = 0;
foreach($fields as $field)
{
$str . = '<a id="a' . $i . '" href="' . $fields['cat_furl'] . '" title="' . $fields['cat_title'] . '">' . $fields['cat_name'] . '</a>';
$i++;
}
$fields['cat_flink'] = $str;
return $fields;
}

if you are counting an array then
echo count($array);
will give the count of every element in the array.

Related

Function to get the embedded content and links from a Wordpress post (from 1 to all of them)

I am making a custom design which I will use with Wordpress (not a theme).
I created a function to get one, more or all embedded items in a post.
It works with <img>, <audio>, <video>, <iframe> and <a> tags, but it can be easily edited to get any html tag.
I use it in a loop:
if (have_posts()) : while (have_posts()) : the_post();
I tested it breefly for all tags and different amounts of items, and it works properly with all but iframes. You can get all other tags.
The function gets the src attribute and then recreates the whole element as needed, with additonal attributes if needed.
I'll post the whole function below, it is a little long.
So I would like to get the iframe source. I tried many different preg_match ways to get it but it did not work.
It's weird that it works with 'video' when it's either written first or in if part... but no iframes.
Since I am neither wordpress nor php developer, any other remarks - be it the security concerns or me doing something wrong - I would really appreciate to be told.
I would also like to know if I use properly ob_start(); and does it help to make this function easier for the server, if there are many visitors at the same time...
Also if there is a better way to make the arguments for the function...
I will add later a wrapper for each individual item, which is very useful (for example create a menu from posts links), and I hope that someone might find it useful, especially when those iframes get fixed.
This is the function:
// $universal_modifier for img size ('thumbnail') or link target '_blank'
// example: get_the_customized_post_content('link', 'all', 'link-class', '_blank');
// example: get_the_customized_post_content('image', 1, 'image-class', 'custom-thumbnail');
function get_the_customized_post_content($item_type = null, $items_num = null, $item_classes = null, $universal_modifier = null)
{
// PHP automatically flushes open output buffers when it reaches the end of a script
ob_start();
global $post;
$single_img = false;
if ($items_num) {
if ($item_type === 'image') {
if ($items_num === 1 && $universal_modifier) {
$single_img = true;
// this will get the featured image, which allows for getting
// the 'full' img with its sourceset
the_post_thumbnail($universal_modifier, array(
'class' => esc_attr($item_classes),
'alt' => esc_html(get_the_title())
));
} else {
preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $item_src);
$additional_attr = '';
$the_html_tag = '<img';
$close_tag = '';
}
} elseif ($item_type === 'audio') {
preg_match_all('/<audio.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->content, $item_src);
$additional_attr = 'preload=none loading=lazy controls';
$the_html_tag = '<audio';
$close_tag = '</audio>';
} elseif ($item_type === 'video') {
preg_match_all('/<iframe.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $item_src);
$additional_attr = 'loading=lazy frameborder=0 allowfullscreen';
$the_html_tag = '<iframe';
$close_tag = '</iframe>';
if (count($item_src[1]) === 0) {
echo 'Getting videos';
preg_match_all('/<video.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $item_src);
$additional_attr = 'preload=metadata loading=lazy controls';
$the_html_tag = '<video';
$close_tag = '</video>';
}
} elseif ($item_type === 'link') {
preg_match_all('/<a.+href=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $item_src);
preg_match_all('/<a.+>([^\'"]+)<\/a>/i', $post->post_content, $anchor_text);
if ($universal_modifier) {
$additional_attr = 'target=' . $universal_modifier;
} else {
$additional_attr = '';
}
$the_html_tag = '<a';
$close_tag = '</a>';
} else {
echo '<p class="' . esc_attr('not-found-info') . '">' . esc_html('Media not found...') . '</p>';
}
}
if ($single_img) {
$display_item = ob_get_clean();
echo $display_item;
} else {
if (count($item_src[1]) === 0) {
echo '<p class="' . esc_attr('not-found-info') . '">' . esc_html('Media not found...') . '</p>';
} else {
$num_of_items = count($item_src[0]);
if ($items_num === 'all') {
$items_total = $num_of_items;
} else {
$items_total = min($num_of_items, $items_num);
// get the smaller number of the two
}
if ($items_total > 0) {
for ($i = 0; $i < $items_total; $i++) {
if ($item_type === 'link') {
$source_type = 'href';
$item_content = $anchor_text;
} else {
$source_type = 'src';
$item_content = '';
}
$the_item = $the_html_tag . ' class="' . esc_attr($item_classes) . '" ' . $source_type . '="' . esc_url($item_src[1][$i]) . '" ' . esc_attr($additional_attr) . '>' . $item_content[1][$i] . $close_tag;
echo $the_item;
};
};
};
}
}
I had to change the function and I think it is better now. It works completely and is easy to use. The function is quite long…
I used var_dump($post->post_content) and saw that there were no iframes in the post content. They get echoed only in the output on the page.
Therefore I used get_media_embedded_in_content() with an appropriate media type to get the desired content, and then preg_match() to get what is needed.
When required only one image per post, the function gets the posts thumbnail 'full' (the post has to have the featured image – there is a plugin for an automatic creation) which returns the image with the sourceset, which makes it responsive. For more images per post it returns the full image size.
I added a wrapper for each individual item, if it's required. It's possible to add classes to it.
It is useful for wrapping images in a <a> tag – it automatically makes the href.
It’s also useful for wrapping links with <li> tags for making menus from the posts links (personally that was one of the most important things for me in this case).
If set link target, it will be used for all links – either links as items or links as wrappers.
Only images can be properly wrapped in <a> tag, others will be wrapped but will not have the href.
If $item_type set to 'video' it will find both <video> and <iframe> tags. It will search for <iframe> first, because it's most likely that everyone will post videos from external sources than self hosted videos.
<video> and <audio> will have controls.
<video> will have preload="metadata", and <audio> preload="none".
<iframe> will have frameborder="0" allowfullscreen.
All except the links will have loading="lazy".
I'm not sure yet if it will work for all of them with wordpress, but it makes no harm... and can be removed later if useless...
As far as I can see, I escaped all html/attribute/url outputs.
The function is called inside the loop, in the category page:
if (have_posts()) : while (have_posts()) : the_post();
get_the_customized_post_content(
$item_type = 'image',
$items_num = 'all',
$item_classes = 'item-image-class class-two',
$item_wrap = 'a',
$item_wrap_classes = 'item-wrap-class one-more-class',
$the_link_target = '_blank'
);
endwhile;
wp_reset_postdata();
endif;
or:
query_posts(array(
'category_name' => 'your-cat-name',
'posts_per_page' => 1
));
if (have_posts()) : while (have_posts()) : the_post();
get_the_customized_post_content(
$item_type = 'audio',
$items_num = 1,
$item_classes = 'item-audio-class',
$item_wrap = 'div',
$item_wrap_classes = 'item-wrap-class classs-two',
$link_target = false
);
endwhile;
wp_reset_postdata();
wp_reset_query();
endif;
$items_num can be 'all' or from 1 to as many as needed - if specified more items than the post has, it will return all the items the post has.
Anything that is not needed, make it false (… $item_wrap = false, …).
Sure there is a better way to write this, to write only those arguments one needs, and leaving out all that are false, but I do not know how to do it.
I would still like to hear the opinions of the wordpress/php developers, especially on the function's performance, and on the coding – I’m sure it can be written better…
Edit:
Improved preg_match_all for links creation.
Added multiple images alt tag.
Also you have to remove:
Featured Image width/height inline attributes
Featured Image Wordpress default classes
// remove Featured Image width/height inline attributes
function remove_img_size_attr($html)
{
$html = preg_replace('/(width|height)="\d+"\s/', "", $html);
return $html;
}
add_filter('post_thumbnail_html', 'remove_img_size_attr', 10);
add_filter('image_send_to_editor', 'remove_img_size_attr', 10);
// remove Featured Image classes
remove_action('begin_fetch_post_thumbnail_html', '_wp_post_thumbnail_class_filter_add');
all in functions.php
OK, the function (place it in functions.php):
function get_the_customized_post_content(
$item_type = null,
$items_num = null,
$item_classes = null,
$item_wrap = null,
$item_wrap_classes = null,
$link_target = null
) {
// PHP automatically flushes open output buffers when it reaches the end of a script
ob_start();
global $post;
$not_found_class = 'media-not-found'; // class for the p tag container for "Nothing found" info
if ($item_type && $items_num) {
if ($item_type === 'video') {
$the_item_media = get_media_embedded_in_content(apply_filters('the_content', get_the_content(), -1), array('video', 'iframe'));
$num_of_items = count($the_item_media);
} elseif ($item_type === 'audio') {
$the_item_media = get_media_embedded_in_content(apply_filters('the_content', get_the_content(), -1), array('audio'));
$num_of_items = count($the_item_media);
} elseif ($item_type === 'image') {
if ($items_num === 1) {
// this will get the featured image, which allows for getting
// the 'full' img with its sourceset
// it's buffered, otherwise it echos automatically
the_post_thumbnail('full', array(
'class' => esc_attr($item_classes),
'alt' => esc_attr(get_the_title())
));
$featured_img = ob_get_clean();
$the_item_url = get_the_post_thumbnail_url(get_the_ID(), 'full');
$num_of_items = 1;
} else {
preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $item_src);
$the_item_media = $item_src[1];
$the_item_url = $item_src[1];
$the_title_attr = $item_src[1];
$num_of_items = count($the_item_media);
};
} elseif ($item_type === 'link') {
preg_match_all('/<a.+href=[\'"]([^\'"]+)[\'"].*>([^\'"]+)<\/a>/i', $post->post_content, $link_parts);
$num_of_items = count($link_parts[0]);
} else {
echo '<p class="' . esc_attr($not_found_class) . '">' . esc_html('Please enter the item type.') . '</p>';
};
} else {
echo '<p class="' . esc_attr($not_found_class) . '">' . esc_html('Please enter the item type and the number of items to return...') . '</p>';
};
if ($num_of_items > 0) {
if ($link_target) {
$link_target_window = 'target=' . esc_attr($link_target);
} else {
$link_target_window = '';
};
if ($items_num === 'all') {
$items_total = $num_of_items;
} else {
$items_total = min($num_of_items, $items_num);
// get the smaller number of the two
};
if ($item_type === 'image') {
if ($items_num === 1) {
if ($item_wrap) {
if ($item_wrap === 'a') {
echo '<a class="' . esc_attr($item_wrap_classes) . '" href="' . esc_url($the_item_url) . '" ' . $link_target_window . '>';
} else {
echo '<' . $item_wrap . ' class="' . esc_attr($item_wrap_classes) . '">';
}
};
echo $featured_img;
if ($item_wrap) {
echo '</' . $item_wrap . '>';
}
} else {
for ($i = 0; $i < $items_total; $i++) {
if ($item_wrap) {
if ($item_wrap === 'a') {
echo '<a class="' . esc_attr($item_wrap_classes) . '" href="' . esc_url($the_item_url[$i]) . '" ' . $link_target_window . '>';
} else {
echo '<' . $item_wrap . ' class="' . esc_attr($item_wrap_classes) . '">';
}
};
$img_src = pathinfo($item_src[1][$i]);
$img_alt_tag = $img_src['filename'];
$fix_filename = array();
$fix_filename[0] = '/-/';
$fix_filename[1] = '/_/';
$fix_filename[2] = '/\s\s+/';
$img_alt_tag = ucwords(preg_replace($fix_filename, ' ', $img_alt_tag));
echo '<img class="' . esc_attr($item_classes) . '" alt="' . esc_attr($img_alt_tag) . '" src="' . esc_url($item_src[1][$i]) . '" loading=' . esc_attr('lazy') . '>';
if ($item_wrap) {
echo '</' . $item_wrap . '>';
}
};
}
} elseif ($item_type === 'link') {
for ($i = 0; $i < $items_total; $i++) {
if ($item_wrap) {
echo '<' . $item_wrap . ' class="' . esc_attr($item_wrap_classes) . '">';
};
echo '<a class="' . esc_attr($item_classes) . '" href="' . esc_url($link_parts[1][$i]) . '" ' . esc_attr($link_target_window) . '>' . esc_html($link_parts[2][$i]) . '</a>';
if ($item_wrap) {
echo '</' . $item_wrap . '>';
};
};
} elseif ($item_type === 'video') {
for ($i = 0; $i < $items_total; $i++) {
preg_match('/<iframe.+src=[\'"]([^\'"]+)[\'"].*>/i', $the_item_media[$i], $item_src);
if ($item_wrap) {
echo '<' . $item_wrap . ' class="' . esc_attr($item_wrap_classes) . '">';
};
if ($item_src[1]) {
echo '<iframe class="' . esc_attr($item_classes) . '" loading="lazy" src="' .
esc_url($item_src[1]) . '" frameborder="0" allowfullscreen></iframe>';
} else {
preg_match('/<video.+src=[\'"]([^\'"]+)[\'"].*>/i', $the_item_media[$i], $item_src);
if ($item_src[1]) {
echo '<video class="' . esc_attr($item_classes) . '" loading="lazy" src="' .
esc_url($item_src[1]) . '" preload="metadata" controls></video>';
} else {
echo '<p class="' . esc_attr($not_found_class) . '">' . esc_html('Media not found.') . '</p>';
};
};
if ($item_wrap) {
echo '</' . $item_wrap . '>';
};
};
} elseif ($item_type === 'audio') {
for ($i = 0; $i < $items_total; $i++) {
preg_match('/<audio.+src=[\'"]([^\'"]+)[\'"].*>/i', $the_item_media[$i], $item_src);
if ($item_wrap) {
echo '<' . $item_wrap . ' class="' . esc_attr($item_wrap_classes) . '">';
};
if ($item_src[1]) {
echo '<audio class="' . esc_attr($item_classes) . '" loading="lazy" src="' .
esc_url($item_src[1]) . '" preload="none" controls></audio>';
} else {
echo '<p class="' . esc_attr($not_found_class) . '">' . esc_html('Media not found.') . '</p>';
};
if ($item_wrap) {
echo '</' . $item_wrap . '>';
};
};
} else {
echo '<p class="' . esc_attr($not_found_class) . '">' . esc_html('Nothing found.') . '</p>';
};
} else {
echo '<p class="' . esc_attr($not_found_class) . '">' . esc_html('Media not found.') . '</p>';
};
};

How do I write a ternary operator for this line?

I can't figure out how to write a ternary operator for the ending of this line (i.e. "location" and "description"). I've defined the $location and $description variables but I'm getting an error that says unexpected $location variable.
Basically, for both location and description, I'm trying to say: If the field has been filled out, display the field. If not, don't print anything.
$content .= '<div data-order="' . $count . '" data-group="' . $group . '"><div class="img-wrap"><img data-iwidth="'.$isize[0].'" data-iheight="' . $isize[1] . '" class="myslide" data-lazy="' . get_template_directory_uri() . '/img/slides/' . strtolower($group) . '/' . $image_url . '" alt="' . get_sub_field('title') . '"><div class="slide-caption"><strong>' . get_sub_field('title') . '</strong><hr>' . get_sub_field('location') ? '<em>'$location'</em>' : ''; . get_sub_field('description') ? '<hr><span class="details">Details [+]</span><div class="details-display">'$description'</div>' : ''; . '</div></div></div>';
Here is the full context:
if( have_rows('slides', $frontpage_id) ):
while ( have_rows('slides', $frontpage_id) ) :
the_row();
$group = get_sub_field('group');
$count = 1;
$i = 0;
$nav .= '<ul id="nav_'.$group.'" style="display: none;">';
$content .= '<div class="image-data-container image-container-'. $group .'">';
while( have_rows('images') ) : the_row(); $count++;
$image_url = get_sub_field('image');
$location = get_sub_field('location');
$description = get_sub_field('description');
$isize = #getimagesize(get_template_directory_uri() . '/img/slides/' . strtolower($group) . '/' . $image_url);
$content .= '<div data-order="' . $count . '" data-group="' . $group . '"><div class="img-wrap"><img data-iwidth="'.$isize[0].'" data-iheight="' . $isize[1] . '" class="myslide" data-lazy="' . get_template_directory_uri() . '/img/slides/' . strtolower($group) . '/' . $image_url . '" alt="' . get_sub_field('title') . '"><div class="slide-caption"><strong>' . get_sub_field('title') . '</strong><hr>' . get_sub_field('location') ? '<em>'$location'</em>' : ''; . get_sub_field('description') ? '<hr><span class="details">Details [+]</span><div class="details-display">'$description'</div>' : ''; . '</div></div></div>';
$nav .= '<li >' . get_sub_field('title') . '</li>';
$i++;
endwhile;
$content .= '</div>';
$nav .= '</ul>';
endwhile;
endif;
?>
Other the fact that your $content variable is a formatting nightmare. The ternary operator syntax returns result based on the condition and it should be separated from your $content attribute
$someVariable = (get_sub_field('location')) ? '<em>'.$location.'</em>' : '';
Now use that some variable inside your $content variable instead
Here is your code with comments:
while( have_rows('images') ) : the_row(); $count++;
$image_url = get_sub_field('image');
// you have already defined the location variable here
// It also means and I am assuming they your get_sub_field is returning a string
// If you are receiving a boolean or null value than and than only than you can do your ternary condition call of
// get_sub_field('location') ? '<em>'$location'</em>' : ''
// and if you are receiving a string field then you will have to explicitly check the condition
// something like this (get_sub_field('location') === '') ? '<em>'$location'</em>' : ''
// I am not that familiar with wordpress framework or the ACF plugin but it looks like get_sub_field will return something so you actually wont need the ternary condition
$location = get_sub_field('location');
// Similar case with description
$description = get_sub_field('description');
$isize = #getimagesize(get_template_directory_uri() . '/img/slides/' . strtolower($group) . '/' . $image_url);
// After removing the ternary condition your content variable will look like this
$content .= '<div data-order="' . $count . '" data-group="' . $group . '"><div class="img-wrap"><img data-iwidth="'.$isize[0].'" data-iheight="' . $isize[1] . '" class="myslide" data-lazy="' . get_template_directory_uri() . '/img/slides/' . strtolower($group) . '/' . $image_url . '" alt="' . get_sub_field('title') . '"><div class="slide-caption"><strong>' . get_sub_field('title') . '</strong><hr>' . '<em>' . $location . '</em>' . '<hr><span class="details">Details [+]</span><div class="details-display">' . $description . '</div>' . '</div></div></div>';
$nav .= '<li >' . get_sub_field('title') . '</li>';
$i++;
endwhile;
You know you can always make it more readable
// You know instead of all the concatenation you can do this instead
$templateDirURI = get_template_directory_uri();
$groupLower = strtolower($group);
$title = get_sub_field('title');
$content .= "<div data-order='{$count}' data-group='{$group}'><div class='img-wrap'><img data-iwidth='{$isize[0]}' data-iheight='{$isize[1]}' class='myslide' data-lazy='{$templateDirURI}/img/slides/{$groupLower}/{$image_url}' alt='{$title}'><div class='slide-caption'><strong>{$title}</strong><hr><em>{$location}</em><hr><span class='details'>Details [+]</span><div class='details-display'>{$description}</div></div></div></div>";
Updated Code
$content .= "<div data-order='{$count}' data-group='{$group}'><div class='img-wrap'><img data-iwidth='{$isize[0]}' data-iheight='{$isize[1]}' class='myslide' data-lazy='{$templateDirURI}/img/slides/{$groupLower}/{$image_url}' alt='{$title}'><div class='slide-caption'><strong>{$title}</strong>";
// Assuming the user did not submit location information
if($location !== "")
$content .= "<hr><em>{$location}</em><hr>";
if($description !== "")
$content .= "<span class='details'>Details [+]</span><div class='details-display'>{$description}</div>";
$content .= "</div></div></div>";

Loop through images not working

With this code, the ID is always 1. I want it to add +1 for each times it loops through the messages.
Like ex1, ex2 ex3 etc. etc.
I cant figure it out whats wrong. Could anyone help?
foreach ($message['attachment'] as $attachment)
{
if ($attachment['is_image'])
{
if ($attachment['thumbnail']['has_thumb'])
echo '<img src="', $attachment['thumbnail']['href'], '" alt="" id="thumb_', $attachment['id'], '" border="0" class="opplastetbilde"/><br />';
else
$id = 1;
if ($id < 10) {
echo '<span class="zoom" id="ex' . $id . '"><img src="' . $attachment['href'] . ';image" alt="" width="' . $attachment['width'] . '" height="' . $attachment['height'] . '" border="0" class="opplastetbilde"/></span><br />';
$id++;
}
}
echo '<img src="' . $settings['images_url'] . '/icons/clip.gif" align="middle" alt="*" border="0" /> ' . $attachment['name'] . ' (', $attachment['size'], ($attachment['is_image'] ? ', ' . $attachment['real_width'] . 'x' . $attachment['real_height'] . ' - ' . $txt['attach_viewed'] : ' - ' . $txt['attach_downloaded']) . ' ' . $attachment['downloads'] . ' ' . $txt['attach_times'] . '.)<br />';
}
move this before foreach or it is always reinitialize $id
$id = 1;
foreach ($message['attachment'] as $attachment)
{
Right now, you're setting $id = 1 each time you loop through the array
foreach ($message['attachment'] as $attachment) {
// ...
$id = 1;
// ...
}
In order to increment it properly, you need to place it before the loop
$id = 1;
foreach ($message['attachment'] as $attachment) {
// ...
}

Remove previous element from array if statement == true

I have a foreach loop that iterates through an array but I want to check if the array contains $item == 'survey-east-upper' and if that's true then hide the previous $item which is 'survey-east'. I've looked into in_array but can't figure how to remove the previous element.
My original code:
foreach ($survey_array->Services as $service) {
foreach ($service as $item) {
echo '<li title="' . rtrim($item) . '" class="' . strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', rtrim($item))) . '">' . $item . '</li>';
}
}
The new code:
foreach ($survey_array->Services as $service) {
foreach ($service as $item) {
if (in_array("survey-east-upper", $survey_array->Services)) {
unset($site->Services['survey-east']);
}
echo '<li title="' . rtrim($item) . '" class="' . strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', rtrim($item))) . '">' . $item . '</li>';
}
}
How can I accomplish this?
Dont use foreach, use for with indexing. In every iteration, look one item ahead and check that item. If its "survey-east-upper", skip actual iteration and continue further.
foreach ($survey_array->Services as $service) {
for ($i = 0; $i < count($service) - 1; $i++) {
$item = $service[$i];
if ($service[$i + 1] == "survey-east-upper") {
continue;
}
echo '<li title="' . rtrim($item) . '" class="' . strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', rtrim($item))) . '">' . $item . '</li>';
}
}
Edit:
You have to do something with last item in array $service[count($service) - 1], because that wont be included in for loop

Add Attribute to First Element in For Loop PHP

I'm wondering how to add an "act" class to the first element in the following for loop?
if (!isset($this->params['page'])){
$this->params['page'] == 1;
}
for($i=1; $i< $news_cont['response']['pager']['total_page']+1; $i++) {
if (isset($this->params['page']) && $this->params['page'] == $i){
$act = 'class="act"';
}else{
$act = '';
}
echo '<a href="/' . $this->params['lang'] . '/' . $this->params['action'] . '/' . $i . '" ' . $act . '>' . $i . '</a>';
}
I need it when $this->params['page'] is not isset the first for cycle element have act class, else class "act" is defined to the element matching $this->params['page'] Thanks for any advice.
for($i=1; $i< $news_cont['response']['pager']['total_page']+1; $i++) {
echo '<a href="/' . $this->params['lang'] . '/' . $this->params['action'] . '/' . $i . '" ' . ((($i == 1) && (!isset($this->params['page'])) ) ? 'class="act"' : '') . '>' . $i . '</a>';
}

Categories