variable issue for return value - php

trying to return $out
$out = '';
$out .= '<form id="agp_upload_image_form" method="post" action="" enctype="multipart/form-data">';
$out .= wp_nonce_field('agp_upload_image_form', 'agp_upload_image_form_submitted');
$out .= $posttile = get_option('posttitle');
$out .= $postdiscription = get_option('postdiscription');
$out .= $postauthor = get_option('postauthor');
$out .= $postcategory= get_option('postcategory');
$out .= $uploadimage= get_option('uploadimage');
$out .= $posttitleenabledisables = get_option('posttitleenabledisables');
$out .= $postdiscriptionenabledisable = get_option('postdiscriptionenabledisable');
$out .= $postauthorenabledisable = get_option('postauthorenabledisable');
$out .= $postcategoryenabledisable = get_option('postcategoryenabledisable');
$out .= $uploadimageenabledisable = get_option('uploadimageenabledisable');
$out .= $posttaxonomies = get_option('posttaxonomies');
$out .= $enablecaptcha = get_option('captchaprivatekey');
if ($posttitleenabledisables == 'disable') { } else {
$out .= '<label id="labels" for="agp_image_caption">"'.if ( isset($posttile[0])) { echo get_option('posttitle'); } else { echo 'Post Title'; } .'":</label><br/>';
$out .='<input type="text" id="agp_image_caption" name="agp_image_caption" value="$agp_image_caption ;"/><br/>';
}
but stuck at this point giving error
$out .= '<label id="labels" for="agp_image_caption">"'.if ( isset($posttile[0])) { echo get_option('posttitle'); } else { echo 'Post Title'; } .'":</label><br/>';
i want this return but getting error because i think variable not allow if else
can some one tell how to fix this

The way you're trying to use if/else, I assume you need a ternary operator. If/else control cannot be used the way you are trying.
Try:
$out .= '<label id="labels" for="agp_image_caption">"'. ( isset($posttile[0]) ? get_option('posttitle') : 'Post Title' ) .'":</label><br/>';
Basically, if-else does not return any value and cannot be used inline. The ternary operator evaluates to a single value and can be concatenated with strings and used inline in any other expression.
$cond ? $true_val : $false_val
If $cond evaluates to true, the entire statement evaluates to $true_val, otherwise $false_val.

Ty Ternaryoperator.
$out .= '<label id="labels" for="agp_image_caption">"';
$out.= (isset($posttile[0]))? get_option('posttitle') : 'Post Title';
$out.='":</label><br/>';

This is because you have a condition in the string concat.
replace
$out .= '<label id="labels" for="agp_image_caption">"'.if ( isset($posttile[0])) { echo get_option('posttitle'); } else { echo 'Post Title'; } .'":</label><br/>';
with
$caption = isset($posttile[0]) ? get_option('posttitle') : "Post Title";
$out = '<label id="labels" for="agp_image_caption">"' . $caption . '":</label><br/>';

Try like
if ( isset($posttile[0])) {
$out .= '<label id="labels" for="agp_image_caption">'. get_option('posttitle').':</label><br/>';
} else {
$out .= '<label id="labels" for="agp_image_caption">Post Title:</label><br/>';
}
In your code remove extra "
Orelse as like your code change like
$out .= '<label id="labels" for="agp_image_caption">'.if ( isset($posttile[0])) { get_option('posttitle') } else { 'Post Title' } .':</label><br/>';

Related

How to efficiently repeat a block of PHP code including a loop?

I would like to repeat the following code 15 times or more on a single page:
$html .= '<select name="select_product_category"
class="dropdown_list"><option value="0">All
categories</option>';
foreach($categories as $value) {
$html .= '<option value="' . $value['category_id'] .
'"';
if($value['category_id'] === $active_category_id)
$html .= ' checked';
$html .= '>' . $value['category_name'] . '</option>';
}
$html .= '</select>';
Is there a better way to achieve this than just repeat this particular block of code? Thanks for your support.
Try to use functions as suggested by #Don't Panic
<?php
function generateSelectBoxHTML()
{
$html = '<select name="select_product_category" class="dropdown_list"><option value="0">All categories</option>';
foreach ($categories as $category) {
$checked = '';
if ($category['category_id'] === $activeCategoryId) {
$checked = ' checked="checked"';
}
$html .= sprintf('<option value="%s"%s>%s</option>', $category['category_id'], $checked, $category['category_name']);
}
$html .= '</select>';
return $html;
}
$html .= generateSelectBoxHTML();
// ...
$html .= generateSelectBoxHTML();
$html .= generateSelectBoxHTML();
$html .= generateSelectBoxHTML();

How to add static li inside dynamic list using php?

I have 5 menu in the website which is coming dynamically :
menu1 menu2 menu3 menu4 menu5
Now I want to add menu6 before menu5 using php.
My code:
foreach ($collection as $category) {
$i++;
$menuCategory = $this->getCategoryAsArray($category, $currentCategory);
$class = '';
$class .= 'nav'. $i;
if($i == 1) {
$class .= ' first';
} elseif ($i == $count) {
$class .= ' last';
}
if($menuCategory['is_active']) {
$class .= ' active';
}
//if($this->hasChildProduct($category)) {
//$class .= ' parent';
//}
if($this->hasChildSubCategory($category)) {
$class .= ' parent';
}
$class .= ' level-top';
$html .= '<li class="level0 '. $class .'">';
$html .= '<a href="'. $menuCategory['url'] .'">';
$html .= '<span>'. $menuCategory['name'] .'</span>';
$html .= '</a>';
//if($this->hasChildProduct($category)) {
//$html .= $this->getChildProductMenuHtml($category, $i);
//}
if($this->hasChildSubCategory($category)) {
$html .= $this->getChildSubcategoryMenuHtml($category, $i);
}
$html .= '</li>';
}
Menu6 is the static link which code is:
<li class="vertical-submenu" id="static-menu"><a href="<?php echo $block->getUrl('menu6')?>"><?php echo __('menu6')?></li>
I am not getting the code because i am not aware of values coming in the array in foreach loop.
But I can explain the situation to you via Algorithm.
$i = 0;
foreach(expression){
if(value == "menu5"){
write("Menu 4")
}
Write("Menu ".$i)
$i++;
}
Hope your problem is resolved with this. If you need anything else or want to elaborate more about you problem text me at shahrukhusmaani#gmail.com

Reinitializing variable in php to NULL

I'm writing a simple gamePage. My Controller method looks like this:
$model = new Game143();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->verifyAnswers();
return $this->render('Game143-confirm', ['model' => $model]);
} else {
$model->initGame(1, 2);
return $this->render('Game143', ['model' => $model]);
}
The else is the important bit. The initGame method is passed the starting level and the max number of levels, so I'm iterating 2 times with random digits and everything works fine.
In my init method I set the value:
public function initGame($level, $numEx) {
$this->maxLevel = $numEx; // normally 10
$this->thisLevel = $level; //normally 1
I also did some output. This works fine and my variable is saved as 2.
In the if method of the controller my variable is suddenly set to NULL?!
Because of this even my results are NULL, because my iteration is <=maxLevel. Anyone know why this happens?
In verifyAnswers(); my given and initialized maxLevel is NULL.
Iterating not possible:
for(; $this->thisLevel <= $this->maxLevel; $this->thisLevel++) {
If i hardcode the maxLevel everything works fine also.
In the view (Working with yii-2):
for($model->thisLevel = 1; $model->thisLevel <= $model->maxLevel; $model->thisLevel++) {
$out .= "\n";
$out .= Html::activeHiddenInput($model,"digit1[$model->thisLevel]");
$out .= "\n";
$out .= Html::activeHiddenInput($model,"digit2[$model->thisLevel]");
$out .= "\n";
$out .= "\n";
$out .= "<h3>Level $model->thisLevel</h3>\n";
$out .= "<h3>max $model->maxLevel</h3>\n";
$out .= "\n";
$out .= "<div class=\"row aufgabenFeld\">";
$out .= "<div align=\"right\" class=\"col-lg-4 col-md-4 col-xs-4 wallLabel \">";
$out .= $model->digit1[$model->thisLevel];
$out .= "</div>";
$out.="<div id='myField__<?php echo $model->thisLevel; ?>' class=\"col-lg-2 col-md-2 col-xs-2 wall\">\n";
$out .= $form->field($model, "proposal[$model->thisLevel]")->label(false);
$out .= "</div>";
$out .= "<div align=\"left\" class=\"col-lg-4 col-md-4 col-xs-4 wallLabel \">"; //id test xD
$out .= $model->digit2[$model->thisLevel];
$out .= "</div>";
$out .= "</div>";
$out .= "<div><br></div>";
In the 'submitView':
foreach ($model->proposal as $key=>$value){
$out .= "<li><h4>Aufgabe $key</h4>";
$out .= $model->digit1[$key];
$out .= " ";
$out .= $model->proposal[$key];
$out .= " ";
$out .= $model->digit2[$key];
$out .= $model->maxLevel[$key];
$out .= "</li>";
}

How can I echo two items per one time by using PHP Foreach?

I'm using PHP to echo my products from the database. If we just use foreach, we will get the result one item per a loop, but actually I want it echo two items per one times as ub the below function.
This is my PHP function using foreach to fetch data from database.
I've used row item selector to wrap product selector, so I want to echo a block of product two times, and then it should echo the row item.
Example: row item = 1 then product = 2
public function last_upated_products() {
$data = $this->newest_products_from_db('products');
$out = '';
if ($data) {
foreach ($data as $k => $row) {
$out .= '<div class="row item">';
$out .= '<div class="product">';
$out .= '<div class="image">';
$out .= '<img src="' . base_url('asset/img/main/9.jpg') . '" alt="img" class="img-responsive">';
$out .= '<div class="promotion"><span class="discount">' . $row['prod_id'] . '% OFF</span> </div>';
$out .= '</div>';
$out .= '<div class="description"><div class="price"><span>$' . $row['prod_price'] . '</span></div><h4>' . $row['prod_name'] . '</h4>';
$out .= '<p>' . $row['prod_descrip'] . '</p>';
$out .= '</div>';
$out .= '</div>';
$out .= '</div>';
}
}
return $out;
}
This function will echo one item for a loop.
You can not print two times in one iteration of a loop. You can use conditional HTML output to do this job.
Consider this:
function last_upated_products() {
$data = $this->newest_products_from_db('products');
$out = '';
$counter = 1;
$length = count($data);
if ($data) {
foreach ($data as $k => $row) {
if ($counter % 2 != 0) {
$out .= '<div class="row item">';
}
$out .= '<div class="product">';
$out .= '<div class="image">';
$out .= '<img src="' . base_url('asset/img/main/9.jpg') . '" alt="img" class="img-responsive">';
$out .= '<div class="promotion"><span class="discount">' . $row['prod_id'] . '% OFF</span> </div>';
$out .= '</div>';
$out .= '<div class="description"><div class="price"><span>$' . $row['prod_price'] . '</span></div><h4>' . $row['prod_name'] . '</h4>';
$out .= '<p>' . $row['prod_descrip'] . '</p>';
$out .= '</div>';
$out .= '</div>';
if ($counter % 2 == 0 || $length == $counter) {
$out .= '</div>';
}
$counter++;
}
}
return $out;
}
You can use the modulus operator to make the check. If your iterator is a multiple of two it will output the appropriate elements (it does this by checking that the remainder is zero):
public function last_upated_products() {
$data = $this->newest_products_from_db('products');
$out = '';
if ($data) {
$i = 0;
foreach ($data as $k => $row) {
if( ($i % 2) === 0) {
$out .= '<div class="row item">';
}
$out .= '<div class="product">';
$out .= '<div class="image">';
$out .= '<img src="' . base_url('asset/img/main/9.jpg') . '" alt="img" class="img-responsive">';
$out .= '<div class="promotion"><span class="discount">' . $row['prod_id'] . '% OFF</span> </div>';
$out .= '</div>';
$out .= '<div class="description"><div class="price"><span>$' . $row['prod_price'] . '</span></div><h4>' . $row['prod_name'] . '</h4>';
$out .= '<p>' . $row['prod_descrip'] . '</p>';
$out .= '</div>';
$out .= '</div>';
if( ($i + 1) % 2 === 0 || ($i + 1) === count($data) ) {
$out .= '</div>';
}
$i++;
}
}
return $out;
}
Note that the last bit ($i + 1) === count($data) is important in the event that your set holds an uneven number.

More efficient way to build dynamic menu

I am creating a dynamic menu whos items appear depending on a set 'mode' (that is passed via ajax). Off this it creates the menu, disabling and hiding icons that are not associated with that mode.
The problem is, in my implementation there are a lot of if conditions. Can anyone show me a cleaner way of doing what I am trying to achieve?
My code is:
public function gridMenu()
{
$mode = Validate::sanitize($_POST['mode']);
$modes = array(
'products' => array('edit', 'delete', 'archive')
);
$output = '<div id="hexContainer">';
for($i = 1; $i < 7; $i++) {
$img = '';
$output .= '<div class="hex hex' . $i;
if($i == 1)
{
if(in_array('edit', $modes[$mode]))
{
$output .= ' hex-selectable';
$img = '<img data-option="Edit" src="' . ROOT . 'images/edit.png">';
} else {
$output .= ' hex-disabled';
}
}
if($i == 2)
{
if(in_array('zzz', $modes[$mode]))
{
$output .= ' hex-selectable';
} else {
$output .= ' hex-disabled';
}
}
if($i == 3)
{
if(in_array('delete', $modes[$mode]))
{
$output .= ' hex-selectable';
$img = '<img data-option="Delete" src="' . ROOT . 'images/delete.png">';
} else {
$output .= ' hex-disabled';
}
}
if($i == 4)
{
if(in_array('xxx', $modes[$mode]))
{
$output .= ' hex-selectable';
} else {
$output .= ' hex-disabled';
}
}
if($i == 5)
{
if(in_array('archive', $modes[$mode]))
{
$output .= ' hex-selectable';
$img = '<img data-option="Archive" src="' . ROOT . 'images/archive.png">';
} else {
$output .= ' hex-disabled';
}
}
if($i == 6)
{
if(in_array('zzz', $modes[$mode]))
{
$output .= ' hex-selectable';
} else {
$output .= ' hex-disabled';
}
}
$output .= '">';
$output .= $img;
$output .= '</div>';
}
$output .= '<div class="hex hex-mid"></div>';
$output .= '</div>';
echo $output;
}
Use the switch function:
switch ($i){
case 1:
//code for $i==1
break;
case 2:
// code for $i==2
break;
//...
}
This hasn't been tested, but you could try something along the lines of this.
Basically from your code I'm assuming that you're trying to insert an image only on the odd rounds. So with that I created a $_modes and $_mode variables which will hold the values for each round.
With these values, we will automatically create the HTML classes using the rules you have set in your code, and on each round if it's odd, and in the array then we also add the image.
public function gridMenu() {
$mode = Validate::sanitize($_POST['mode']);
$modes = array(
'products' => array('edit', 'delete', 'archive')
);
$_modes = array(
false,
array('Edit', 'edit'),
array('ZZZ', 'zzz'),
array('Delete', 'delete'),
array('XXX', 'xxx'),
array('Archive', 'archive'),
array('ZZZ', 'zzz'),
);
$output = '<div id="hexContainer">';
for($i = 1; $i < 7; $i++) {
$_mode = $_modes[$i];
$img = '';
$classnames = array('hex', 'hex' . $i);
if ( ($i % 2) === 0 && in_array($_mode[1], $modes[$mode])) {
$img = '<img data-option="' . $_mode[0] . '" src="' . ROOT . 'images/' . $_mode[1] . '.png">';
}
$classnames[] = (in_array($_mode[1], $modes[$mode]) ? 'hex-selectable' : 'hex-disabled');
$output .= '<div class="' . implode(' ', $classnames) . '">';
$output .= $img;
$output .= '</div>';
}
$output .= '<div class="hex hex-mid"></div>';
$output .= '</div>';
echo $output;
}

Categories