Is this an array with foreach? - php

I have three variables ($var, $var2 & $var3) and I want it to output when they have value.
For example, if $var = "Data"; then:
<ul>
<li>Data</li>
</ul>
And if any of the other variables has value then:
<ul>
<li>Data</li>
<li>Data2</li>
</ul>
Or
<ul>
<li>Data</li>
<li>Data3</li>
</ul>
<ul>
<li>Data</li>
<li>Data3</li>
<li>Data2</li>
</ul>
I am not exactly sure how to create this and with what method considering everybody has different ways of doing their php code. Does anybody know how I can create this?
Also: I use http://writecodeonline.com/php/ when testing certain php codes.

<ul>
<?php foreach (array($var1, $var2, $var3) as $var) : ?>
<?php if (!empty($var)) : ?>
<li><?php echo $var; ?></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
You can see the output here on writecodeonline.com.
Or maybe you prefer this:
<ul>
<?php
foreach (array($var1, $var2, $var3) as $var) {
if (!empty($var)) {
echo '<li>' . $var . '</li>';
}
}
?>
</ul>
(it doesn't matter really, just use whatever you think looks better)

You can try:
<ul>
<?php foreach(array($var, $var2, $var3) as $value) : ?>
<?php if (!empty($value)) : ?>
<li><?php echo $value; ?></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>

I suppose from the title that your variables are inside an array.
If so, just do a foreach loop
foreach($arrayVars as $var)
{
if(isset($var))
{
echo '<li>'.$var.'</li>
}
}
Anyway, you should explain clearly what your problem is. I making assumptions here because your not very explicit on what your problem is.

Use an array, and foreach to print the variables.
http://php.net/manual/en/language.types.array.php
or you can use this (what I not recommend):
if(isset($var)) {
echo $var;
}
if(isset($var1)) {
echo $var1;
}
if(isset($var2)) {
echo $var2;
}
Best is var-args in my opinion.
function funcName() {
for ($i = 0;$i < func_num_args();$i++) {
echo '<li>'.func_get_arg($i).'</li>';
}
echo funcName($var,$var1,$var2);

Related

Check if URL = Desired URL (PHP)

I'm trying to check if the current URL equals the desired URL for making the link class active (Bootstrap).
Example
<?php
If ($currenturl = "show.php?name=123") {
?><li class="active">123</li><?php
}else{
?><li class="">123</li><?php
}
?>
Current URL -> $currenturl = $_SERVER['REQUEST_URI']
Now, I have this if I'm on show.php?name=456
Make sure you have the correct comparison inside the if. You're currently using the assignment operator:
Note the difference:
if($currenturl = "show.php?name=123") // assignment =
// changes $currenturl to "show.php?name=123"
// and then tests if("show.php?name=123") equivalent to if(true)
// see also http://stackoverflow.com/questions/5940626/evaluation-of-assignment-in-php
if($currenturl == "show.php?name=123") // comparison ==
Second: You have set $urlpage but comparing $currenturl. Use $urlpage
Code:
<?php $urlpage = $_SERVER['REQUEST_URI']; ?>
<?php if ($urlpage == "/show.php?nom=123") { ?>
<li class="active">123</li>
<?php } else { ?>
<li class="">123</li>
<?php } ?>
An alternative using a ternary operator:
<li <?php echo ($urlpage == "/show.php?nom=123") ? 'class="active"' : ''; ?>>123</li>
Applying to all pages:
<?php $pages = array('123', '456', '789'); ?>
<ul>
<li <?php echo (!isset($_GET['nom']) ? 'class="active"' : ''); ?>>Home</li>
<?php foreach($pages as $page): ?>
<?php if (isset($_GET['nom']) && $_GET['nom'] == $page) { ?>
<li class="active"><?php echo $page; ?></li>
<?php } else { ?>
<li class=""><?php echo $page; ?></li>
<?php } ?>
<?php endforeach; ?>
</ul>
An alternate way is to use the $_GET
if(isset($_GET['name']))
if($_GET['name'] == '123')
...
and so forth

Error with php switch function

I´ve got the following code and when I paste the code to my page, I get a white page, can you guys help me?
PHP
<?php $strRendersettings = ($this->settings)? 'settings' : 'view'; ?><?php if (count($this->data)): ?>
<ul>
<?php
switch($_SERVER['HTTP_HOST'])
{
case ("www.domain.de"):
foreach ($this->data as $arrItem): ?>
<li class="new_doc_home"><a href=""; ?>" ><strong><?php echo $arrItem['text']['new_docs_titel']; ?>:</strong><br>
<p><?php echo $arrItem['text']['new_docs_Text']; ?></p></a>
</li>
<?php
break;
case ("www.domain.com"):
foreach ($this->data as $arrItem): ?>
<li class="new_doc_home"><a href=""; ?>" ><strong><?php echo $arrItem['text']['new_docs_titel']; ?>:</strong><br>
<p><?php echo $arrItem['text']['new_docs_Text']; ?></p></a>
</li>
<?php
break;
case ("www.domain.fr"):
foreach ($this->data as $arrItem): ?>
<li class="new_doc_home"><a href=""; ?>" ><strong><?php echo $arrItem['text']['new_docs_titel']; ?>:</strong><br>
<p><?php echo $arrItem['text']['new_docs_Text']; ?></p></a>
</li>
<?php
break;
}
?>
<?php endforeach; ?>
</ul>
<?php else: ?>
<?php endif; ?>
I need the code because of some different top level domains.
Thanks :)
The porblem is that you never end you foreach loops.
You should end each foreach: loop with endforeach;. Now you have 3 loops and only one closing endforeach;
For example this code works without a problem:
<?php
$array = [1=>2, 3=> 4];
$array2 = [5=>6,7=>8];
foreach ($array as $k => $v):
foreach ($array2 as $i => $j):
echo $i.' '.$j."<br />";
endforeach;
endforeach;
while the following doesn't:
<?php
$array = [1=>2, 3=> 4];
$array2 = [5=>6,7=>8];
foreach ($array as $k => $v):
foreach ($array2 as $i => $j):
echo $i.' '.$j."<br />";
//endforeach;
endforeach;
I advice you also to add at the beginning of your PHP file:
<?php
error_reporting(E_ALL);
ini_set('display_errors','1');
to have all warnings and error displayed. Of course on production you should disable error reporting
It looks like you're breaking the foreach loop with the break of the switch. You should end the foreach inside each case of the switch.
See you PHP error log for error messages. When there is a parse error, the page is shown blank, and the error message goes to the PHP error log.
In your code, <?php endforeach; ?> appears to be outside the switch. I guess each foreach should have its own endforeach before the switch's break.
Correct me if I'm wrong, but you are doing the exact same thing for each of the three scenarios. I would alter my code to this:
<?php $strRendersettings = ($this->settings)? 'settings' : 'view'; ?>
<?php if (count($this->data)): ?>
<ul>
<?php
switch($_SERVER['HTTP_HOST'])
{
case "www.domain.de":
case "www.domain.com":
case "www.domain.fr":
foreach ($this->data as $arrItem): ?>
<li class="new_doc_home">
<a href="">
<strong>
<?php echo $arrItem['text']['new_docs_titel']; ?>:
</strong><br>
<p>
<?php echo $arrItem['text']['new_docs_Text']; ?>
</p>
</a>
</li>
<?php
endforeach;
break;
}?>
</ul>
You need to add endforeach statement before every break statement. Add that and your error will get sloved.
Hope this help :)

Hide if get_the_category() returns no results

I'm listing related pages based on category. This is what I'm using to list all related categories. What I'm trying to do is hide the entire block if it doesn't return any categories. I'm not sure how to do that with the foreach.
<h3>Related Category</h3>
<ul>
<?php foreach((get_the_category()) as $catCS) {
if($catCS->parent == 4){ ?>
<li><?php echo $catCS->cat_name; ?></li>
<?php }
} ?>
</ul>
Not sure if you know, but WordPress have a command to get parent categories get_category_parents, so if you use that you could use it like this:
<?php
$result = get_category_parents($cat, true, '</li><li>');
$result = substr($result, 0, -4);
if(!is_wp_error($result))
{
?>
<h3>Related Category</h3>
<ul>
<li><?php echo $result; ?>
</ul>
<?php
}
?>
NOTE: substr is a small hack to remove the last empty <li> opening due to how I am using </li><li> as a separator.
This is untested, but you could filter the current array into a resulting array and test if that is empty or not.
<?php
# save the result
$categories = array();
# fill $categories if any match
foreach ((get_the_category()) as $cat)
{
if($cat->parent == 4)
{
$categories[] = $cat;
}
}
# print nothing if $categories is empty
if (!empty($categories))
{
?>
<h3>Related Category</h3>
<ul>
<?php
foreach($categories as $catCS)
{
?>
<li><?php echo $catCS->cat_name; ?></li>
<?php
}
?>
</ul>
<?php
}
?>
There might be a better way but this should work.

Passing an array of variables FROM an object

So here's what I want to do, I have a class and within SomeClass, there's a function consists of 2 variables, each has a numerical value. I want to return an array of the two variables which have dependencies in post data outside of SomeClass from a form that posts to itself.
<?php
class SomeClass{
private $someVar1;
private $someVar2;
public function setVars($var1,$var2) {
$this->someVar1 = $var1;
$this->someVar2 = $var2;
}
function __construct() {
}
function setFraction() {
$sum['num'] = 140*pow($this->someVar1,0.75);
$sum['den'] = $sum['num']/$this->someVar2;
return $sum;
}
}
if(isset($_POST['num'])){$num = preg_replace('/\D/', '', $_POST['num']);}
elseif(isset($_POST['den'])){$den = preg_replace('/\D/', '', $_POST['den']);}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Numerator:<input type="text" value="<?php if(isset($num)){echo $num;}?>" name="num" /><br />
Denominator:<input type="text" value="<?php if(isset($den)){echo $den;}?>" name="den" /><br />
<input type="submit" value="Go" name="Go">
</form>
<?php if(isset($num,$den)):
$obj = new SomeClass();
$obj->setVars($num,$den);
$sum=$obj->setFraction();?>
<pre>
<?php print_r($obj->setFraction());?>
</pre>
<ul>
<?php foreach($sum as $val):?>
<li><?php echo $val['num']?></li>
<li><?php echo $val['den']?></li>
<?php endforeach;?>
</ul>
<?php endif;?>
When I run the script, post data for $num and $den is being sent and returned with setFraction(), however when I try to iterate through the array in a foreach loop, I don't get any return data. I'm sure its something simple, I've tried it with a foreach loop and without with same results, any help would be excellent, thx.
EDIT:
<?php if(isset($num,$den)):
$obj = new SomeClass();
$obj->setVars($num,$den);
$array = $obj->setFraction();?>
<ul>
<li><?php echo $array['num']?></li>
<li><?php echo $array['den']?></li>
</ul>
<?php endif;?>
Store the returned data to some variable,and then iterate.
//
<?php if(isset($num,$den)):
$obj = new SomeClass();
$obj->setVars($num,$den);
$array = $obj->setFraction();?>
<ul>
<?php foreach($array as $val):?>
<li><?php echo $val['num']?></li>
<li><?php echo $val['den']?></li>
<?php endforeach;?>
</ul>
<?php endif;?>
you haven't assign $sum=$obj->setFraction(); to $sum
auYou're not assigning the return values of $obj->setFraction() to a variable. You need to do:
$sum=$obj->setFraction();
and all should be OK.
Just becuase you're returning a variable called $sum doesn't mean that that variable name is used once it's back in the main body of your script.
I have just noticed, as you rightly state in your acceptance, that you don't need the foreach block. Just use $sum['num'] and $sum['den']. Sorry about that - I should have noticed earlier
You should use $obj->sum instead of $sum.

How can I comment this particular block of PHP code?

How would I go about commenting all of this code when it has breaks in the PHP sections?
If I wrap /* */ around it, it doesn't work.
Obviously I can make it work by not being lazy, but if I want to be lazy... How might you comment this whole block?
if($fields){
?>
<ul>
<?php
foreach($fields as $field){
?>
<li>
<?php
/* if($field['label']){
echo $field['label'];
} */
print_ext($field);
?>
</li>
<?php
}
?>
</ul>
<?php
}
You can't really but you can turn it off pretty easily.
if($fields && false){
?>
<ul>
<?php
foreach($fields as $field){
?>
<li>
<?php
/*if($field['label']){
echo $field['label'];
}*/
print_ext($field);
?>
</li>
<?php
}
?>
</ul>
<?php
}
The following solution should work. You might have issues if you are wrapping the comments that exist already around if($field['label']) so I have deleted them as shown below.
<?php
/*
if($fields){
?>
<ul>
<?php
foreach($fields as $field){
?>
<li>
<?php
if($field['label']){
echo $field['label'];
}
print_ext($field);
?>
</li>
<?php
}
?>
</ul>
<?php
}
*/
?>
For more information look at this answer.
Put your HTML within the PHP open/close tags and then the /* */ will work fine.
Not really commenting, but you can disable this block like this (almost no matter its content):
<?php $bar = <<<'EOD'
if($fields && false){
?>
<ul>
<?php
foreach($fields as $field){
?>
<li>
<?php
/*if($field['label']){
echo $field['label'];
}*/
print_ext($field);
?>
</li>
<?php
}
?>
</ul>
<?php
}
EOD;

Categories