Add Attribute to First Element in For Loop PHP - 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>';
}

Related

How to add a new line in textarea element in php code?

I want to add a newline in a textarea. I tried with < p> tag but it's not working. Can you help me to insert a newline in a textarea? Please find the code above for a generic contact form. Where should I add tags for line breaks here?
public function cs_form_textarea_render($params = '') {
global $post, $pagenow;
extract($params);
if ( $pagenow == 'post.php' ) {
$cs_value = get_post_meta($post->ID, 'cs_' . $id, true);
} else {
$cs_value = $std;
}
if ( isset($cs_value) && $cs_value != '' ) {
$value = $cs_value;
} else {
$value = $std;
}
$cs_rand_id = time();
if ( isset($force_std) && $force_std == true ) {
$value = $std;
}
$html_id = ' id="cs_' . sanitize_html_class($id) . '"';
$html_name = ' name="cs_' . sanitize_html_class($id) . '"';
if ( isset($array) && $array == true ) {
$html_id = ' id="cs_' . sanitize_html_class($id) . $cs_rand_id . '"';
$html_name = ' name="cs_' . sanitize_html_class($id) . '_array[]"';
}
$cs_required = '';
if ( isset($required) && $required == 'yes' ) {
$cs_required = ' required="required"';
}
$cs_output = '<div class="' . $classes . '">';
$cs_output .= ' <textarea' . $cs_required . ' rows="5" cols="30"' . $html_id . $html_name . ' placeholder="' . $name . '">' . sanitize_text_field($value) . '</textarea>';
$cs_output .= $this->cs_form_description($description);
$cs_output .= '</div>';
if ( isset($return) && $return == true ) {
return force_balance_tags($cs_output);
} else {
echo force_balance_tags($cs_output);
}
}
Just add a "\n" char somewhere between your text area tags
$cs_output .= ' <textarea' . $cs_required . ' rows="5" cols="30"' . $html_id . $html_name . ' placeholder="' . $name . '">' . sanitize_text_field($value) . "\n" . "this text is on a new line". '</textarea>';
You will try to add "\n" before your end position of the tag. You need to concatenate Like ."\n".

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>";

Making selected value of option with php

I want to make a code which demonstrates that if I choose any option value and press submit button, the value which I chose should be seen in the options box.
The codes are;
<?php
$myfile = fopen("cars_lab5.txt", "r") or die("Unable to open file!");
?>
This is to open the file because I pull the items from a file.
<?php
$index = 0;
$val = $_GET['car'];
//$selection = "";
for ($index=0 ; $index < 5 ; $index++){
$num = 0;
$line = fgets($myfile) . "<br>";
$slide = explode("|",$line);
//echo '<option value="' . $index . '">' . $slide[$num] . ' - ' . $slide[num+1] . ' euros';
if ($val==0){
echo '<option value="' . $index . '"' . $selection . ' selected">' . $slide[$num] . ' - ' . $slide[num+1] . ' euros'; }
else if ($val==1){
echo '<option value="' . $index . '"' . $selection . ' selected">' . $slide[$num] . ' - ' . $slide[num+1] . ' euros'; }
else if ($val==2){
echo '<option value="' . $index . '"' . $selection . ' selected">' . $slide[$num] . ' - ' . $slide[num+1] . ' euros'; }
else if ($val==3){
echo '<option value="' . $index . '"' . $selection . ' selected">' . $slide[$num] . ' - ' . $slide[num+1] . ' euros'; }
else if ($val==4){
echo '<option value="' . $index . '"' . $selection . ' selected">' . $slide[$num] . ' - ' . $slide[num+1] . ' euros'; }
}
fclose($myfile);
?>
When I use this code, everything works properly but if I choose third option and press submit button, again first item is seen on the option box instead of what I choose.
You have set all options with the 'selected' tag, so the browser will show the last option as selected by default.
You need to remove the 'selected' string from the echo statement and configure the $selection var somewhere:
$selection=($index==$val?'selected':null)
You don't need the if/else statement at all.
So you would just have one line:
echo '<option value="' . $index . '"' . $selection . '">' . $slide[$num] . ' - ' . $slide[num+1] . ' euros';
EDIT including example as per comment
Your example code will look like:
<?php
$index = 0;
$val = $_GET['car'];
//$selection = "";
for ($index=0 ; $index < 5 ; $index++){
$num = 0;
$line = fgets($myfile) . "<br>";
$slide = explode("|",$line);
$selection=($index==$val?'selected':null);
echo '<option value="' . $index . '"' . $selection . '">' . $slide[$num] . ' - ' . $slide[num+1] . ' euros';
}
fclose($myfile);
?>

PHP Leaderboard add (t) for ties

I have a php leaderboard and it works great, and works well with ties. Currently it will number users from 1st to last place (whichever # that is), and if there are ties, it lists them all out with the same number.
For example:
userC 2. userG 3. userA 3. userT 3. userJ 4. userW 5. userP
What I would like is for when there are ties, for the leaderboard to display a "(t)" next to the number, like so: (t) 3. userT
Here is my code, any help is appreciated:
<table cellpadding="4" cellspacing="0" class="table1" width="100%"><caption>
<h2>Leaderboard</h2>
</caption>
<tr><th align="left">Player</th><th align="left">Wins</th><th>Pick Ratio</th></tr>
<?php
if (isset($playerTotals)) {
$playerTotals = sort2d($playerTotals, 'score', 'desc');
$i = 1;
$tmpScore = 0;
//show place #
foreach($playerTotals as $playerID => $stats) {
if ($tmpScore < $stats[score]) $tmpScore = $stats[score];
//if next lowest score is reached, increase counter
if ($stats[score] < $tmpScore ) $i++;
$pickRatio = $stats[score] . '/' . $possibleScoreTotal;
$pickPercentage = number_format((($stats[score] / $possibleScoreTotal) * 100), 2) . '%';
//display users/stats
$rowclass = ((($i - 1) % 2 == 0) ? ' class="altrow"' : '');
echo ' <tr' . $rowclass . '><td style="height: 25px;"><b>' . $i . '</b>. ' . $stats[userName] . '</td><td align="center">' . $stats[wins] . '</td><td align="center">' . $pickRatio . ' (' . $pickPercentage . ')</td></tr>';
$tmpScore = $stats[score];
}
}
echo ' </div>' . "\n";
?>
</table>
Try this code... hope it will resolve your issue
<table cellpadding="4" cellspacing="0" class="table1" width="100%">
<caption><h2>Leaderboard</h2></caption>
<tr><th align="left">Player</th><th align="left">Wins</th><th>Pick Ratio</th></tr>
<?php
if (isset($playerTotals)) {
$playerTotals = sort2d($playerTotals, 'score', 'desc');
$j = 1;
$tmpScore = 0;
//show place #
$tieflag=false;
for($i=0; $i<=count($playerTotals)-1; $i++) {
if(($i<count($playerTotals) && $playerTotals[$i][score]==$playerTotals[$i+1][score]) || ($i>0 && $playerTotals[$i][score]==$playerTotals[$i-1][score])) $tieflag=true;
$pickRatio = $$playerTotals[$i][score] . '/' . $possibleScoreTotal;
$pickPercentage = number_format((($playerTotals[$i][score] / $possibleScoreTotal) * 100), 2) . '%';
$rowclass = ((($j - 1) % 2 == 0) ? ' class="altrow"' : '');
echo ' <tr' . $rowclass . '><td style="height: 25px;"><b>' . ($tieflag?'(t)'.$j:$j) . '</b>. ' . $playerTotals[$i][userName] . '</td><td align="center">' . $playerTotals[$i][wins] . '</td><td align="center">' . $pickRatio . ' (' . $pickPercentage . ')</td></tr>';
$j++;
}
}
echo '</div>'. "\n";
?>
</table>
I'd create a new variable $placeholder. So:
if ( $i != 0 ) {
if ($tmpScore < $stats[score]) {
$tmpScore = $stats[score];
}
if ( $tmpScore == $stats[score] ) {
$placeholder = $i.'(t)';
} else if ($stats[score] < $tmpScore )
$placeholder = $++i;
}
} else {
$placeholder = $++i;
$firstScore = $stats[score];
$tmpScore = $stats[score];
}
Then instead of printing $i print $placeholder
so for the first time through you could do this in the echo:
//It makes more sense if you read it from bottom to top but I put it this way
//so you will not have to keep running through every condition when you will
//only evaluate the first condition most often
if ( $i != 0 && $i != 1 ) {
echo ;//Your normal print
} else if ( $i = 1 && $tmpScore != $firstScore ) {
echo '<b>'; //and the rest of the first line plus second line NOT a tie
} else if ( $i = 1 ) {
echo ' (t)'; //Plus the rest of your first line plus second line TIE
} else {
//This is your first time through the loop and you don't know if it's a tie yet so just
//Print placeholder and then wait to figure out the rest
echo ' <tr' . $rowclass . '><td style="height: 25px;"><b>' . $placeholder;
}

How to count each field in 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.

Categories