Create multiple strings based on elseif condition in php - php

While this code seems to work to change $tdstyle as anticipated on the td line, it does not update $font and $text appropriately based on the esleif conditions. It always seems to keep these strings the same based on the else condition alone even if it isn't true. Maybe just a syntax issue? I am certain there is a much better way to do this, but my limited knowledge has brought me to this point. Any suggestions?
<?php
$num = (float)$uvindex;
if($num >10) {
$tdstyle='#B567A4';
$font='white';
$text='Extreme';
} elseif($num >=8) {
$tdstyle='#E53210';
$font='white';
$text='Very High';
} elseif($num >=6) {
$tdstyle='#F18B00';
$font='black';
$text='High';
} elseif($num >=3) {
$tdstyle='#FFF300';
$font='black';
$text='Moderate';
} else $tdstyle='#3EA72D'; $font='black'; $text='Low';
?>
<td height="82" colspan="2" align="center" valign="middle" class="data1" style="text-align:center; background-color:<?php echo $tdstyle ?>; color:<?php echo $font ?>; border: 3px solid black; border-radius: 7px; font-size:12px;">

Your else is only containing the first statement (where you set $tdstyle).
This
// ...
} else $tdstyle='#3EA72D'; $font='black'; $text='Low';
is equivalent to
// ...
} else {
$tdstyle='#3EA72D';
}
$font='black'; // you probably want these in the
$text='Low'; // above else block
So $font and $text will always be 'black' and 'Low' respectively. Remember that ; terminates a statement, not a newline. Listen to the comments of Nigel: invest in a formatter to help you catch errors like these.

Related

Email always takes the `if` and not the `else if`/`else` path

I have a function in my website where you can buy stuff. After you do that, you will get an email. Everything works fine except for one thing. I have an ifstatement in my code, but it always takes the if and not the else if or else path.
I searched on the Internet but I couldn't find any solution. I tried different things in my else if like else if (isset empty($registrationInfo['serviceselectoptie']) and else if (isset ($registrationInfo['serviceselectoptie'] === NULL) but that didn't work.
My if statement
<?php
$registrationInfo = $connect->select(
"SELECT * FROM `registrationinfo` WHERE `orderId`= '".$order_id."' LIMIT 1"
)->fetch();
if (
isset($registrationInfo['serviceselectoptie']) AND
isset($registrationInfo['serviceconsult'])
) {
$titellist = '<tr><td bgcolor="#DEDEDE" style="padding: 5px 5px 5px 5px;width:175px;">'
.$registrationInfo['serviceselectoptie'].':</td><td style="padding: 5px 5px 5px 5px;">'
.$registrationInfo['serviceconsult'] .'</td></tr>';
} else if (
!isset($registrationInfo['serviceselectoptie']) AND
isset($registrationInfo['serviceconsult'])
) {
$titellist = '<tr><td bgcolor="#DEDEDE" style="padding: 5px 5px 5px 5px;width:175px;">'
.'Bestelling:</td><td style="padding: 5px 5px 5px 5px;">'
.$registrationInfo['serviceconsult'].'</td></tr>';
} else {
$titellist = "";
}
?>
What I expect is that if the $registrationInfo['serviceselectoptie'] row is empty (null), it will go to the else if. My actual output is that it takes the if path and because the row is empty it will just give :
Example of output
As you are checking the details in a result set, you will find that they will always be set, what you may want instead is to check if the value is empty(), as you want to make sure there is a value though - you will have to say if !empty() to check if it has a value...
if(!empty($registrationInfo['serviceselectoptie'])
AND !empty($registrationInfo['serviceconsult']))
apply this to the other parts of the code as well.
isset($registrationInfo['serviceselectoptie']) is truthy when serviceselectoptie key exists in the array and is set to either an empty string or a value other than NULL.
// php -a
// Interactive shell
> $test = ['a'=>2, 'b'=>null, 'c'=>''];
> echo isset($test['a']);
1
> echo isset($test['b']);
> echo isset($test['c']);
1
A better check is using empty function.
// php -a
// Interactive shell
> $test = ['a'=>2, 'b'=>null, 'c'=>''];
> echo empty($test['a']);
> echo empty($test['b']);
1
> echo empty($test['c']);
1
> echo empty($test['d']); // non-existent key
1
> echo empty(NULL['a']); // yes NULL can be indexed
1
This way the branches in your code will be as:
if(
!empty($registrationInfo['serviceselectoptie'])
AND !empty($registrationInfo['serviceconsult'])) {
//...
}
else if(
empty($registrationInfo['serviceselectoptie'])
AND !empty($registrationInfo['serviceconsult'])) {
//...
}
else {
//...
}

php regex select less code

I want to select all less code from a file .But i can not find the right way to do it.
This is my code so far
$d = <<<EOT
.class {
width:100%;
height:100%;
background-image: url(images/fallback-gradient.png);
}
.id {
b:100%;
bc: url(images/fallback-gradient.png);
}
& when ( #main_container_top_option = true) {
.fast_menu_option {
.gpicon {
color: transparent;
}
}
}
EOT;
$pattern = '/.*\{(?s:.*?)\}$/mi';
$t = preg_match_all($pattern, $d, $out, PREG_PATTERN_ORDER);
foreach ($out[0] as $key) {
echo '<br><pre>'.$key."</pre>";
}
And this is the result:
.class {
width:100%;
height:100%;
background-image: url(images/fallback-gradient.png);
}
.id {
b:100%;
bc: url(images/fallback-gradient.png);
}
& when ( #main_container_top_option = true) {
.fast_menu_option {
.gpicon {
color: transparent;
}
For the first 2 classes is ok but last one is not ok because they are missing 2 other }.
How can i fix it?
It looks like you want to match individual blocks, so a recursive pattern will return balanced braces. As stated in comments under the question, this method may break when character anomalies occur. I believe there are css parsers out "in the wild" but I don't have any to recommend.
Code: (Demo)
if (preg_match_all('~.*\{((?R)|[^}])*}~', $d, $out)) {
echo implode("\n---\n",$out[0]);
}
Output:
.class {
width:100%;
height:100%;
background-image: url(images/fallback-gradient.png);
}
---
.id {
b:100%;
bc: url(images/fallback-gradient.png);
}
---
& when ( #main_container_top_option = true) {
.fast_menu_option {
.gpicon {
color: transparent;
}
}
}
If you don't need to separate the blocks, you can modify the pattern like this:
~[^{]*\{((?R)|[^}])*}~
But then it depends on what your actual input.

PHP script printing div

Is there a possible way to multiply code and print it out using PHP?
I am trying to make a script that checks users and draws a line depending on count.
CSS Code
#outer { // gray backround - always on.
background-color: #401800;
width: 150px;
height: 6px;
}
.inner { // used if there's less than 100 ppl online
width: 1px;
height: 6px;
display:block;
float:left;
}
.bigger { // used if 100+ people are online
width: 10px;
height: 6px;
display:block;
float:left;
}
}
.bigger.trys { // color for small px
background-color: green;
}
.inner.vienas { //color for big px
background-color: green;
}
PHP code ($rows = counted users):
if {$rows <= "0"
echo"<span class="inner vienas"></span>"; //draws small 1px width bar
}
elseif{$rows >= "10"
echo"<span class="inner vienas"></span><span class="inner vienas"> </span>"; // count =10 or greater - draws x2 bars.
}
elseif{$rows >= "100" // if users are 100 OR more counts new variable
$padala = $rows/10 //variable is users/10
echo 10*"<span class="bigger trys"></span>") //i want to print this out as 1px each 10 users
}
else {
echo "Script error";
}
Is there a way to do that?
Basicly you have lot of syntax error.
First, if statement need a condition:
Wrong:
if {
$rows <= "0"
echo"<span class="inner vienas"></span>"; //draws small 1px width bar
}
Correct (i don't know if $row have an integer or string, but if you use numbers, the correct is to storage an integer):
if ($rows <= 0) {
echo '<span class="inner vienas"></span>';
}
Second, echo:
You have an error with double quote marks when inserting HTML code, you don't have to cut the echo
Wrong:
echo"<span class="inner vienas"></span>";
Correct (using simple quotes):
echo '<span class="inner vienas"></span>';
Another error is that echo*10, you need to use a for loop.
for($i=0; $i<=9; $i++) {
echo '<span class="bigger trys"></span>';
}
Btw, I don't understand what you want, but the correct maybe is this:
if ($rows <= 0) {
echo '<span class="inner vienas"></span>';
} else if ($rows >= 10) {
echo '<span class="inner vienas"></span><span class="inner vienas"> </span>';
} else if ($rows >= 100) {
$padala = $rows / 10
for($i=0; $i<=9; $i++) {
echo '<span class="bigger trys"></span>';
}
} else {
echo "Script error";
}
Here you can read more about if statements and for:
PHP Manual - If Statements
PHP W3Schools - For loops
Without knowing more about your data, I'm not sure how I would go about doing what you want to accomplish. However, Here is your above code with the syntax fixes.
The conditions in the if statements should be wrapped in Parentheses, and the double quotes in the strings after the the echo functions should be escaped
if ($rows <= "0") {
echo"<span class=\"inner vienas\"></span>"; //draws small 1px width bar
} elseif($rows >= "10") {
echo"<span class=\"inner vienas\"></span><span class=\"inner vienas\"> </span>"; // count =10 or greater - draws x2 bars.
} elseif($rows >= "100") { // if users are 100 OR more counts new variable
$padala = $rows/10 //variable is users/10
echo 10*"<span class=\"bigger trys\"></span>") //i want to print this out as 1px each 10 users
} else {
echo "Script error";
}

Make var_dump look pretty [duplicate]

This question already has answers here:
Is there a pretty print for PHP?
(31 answers)
Closed 7 months ago.
I have a simple $_GET[] query var set for showing testing data when pulling down queries from the DB.
<?php if($_GET['test']): ?>
<div id="test" style="padding: 24px; background: #fff; text-align: center;">
<table>
<tr style="font-weight: bold;"><td>MLS</td></tr>
<tr><td><?php echo KEY; ?></td></tr>
<tr style="font-weight: bold;"><td>QUERY</td></tr>
<tr><td><?php echo $data_q; ?></td></tr>
<tr style="font-weight: bold;"><td>DATA</td></tr>
<tr><td><?php var_dump($data); ?></td></tr>
</table>
</div>
<?php endif; ?>
When I do var_dump, as expected it's this big array string that is all smushed together. Is there a way to add in line breaks at least for this or display the var_dump in a way that's more readable? I'm open to jQuery suggestions on manipulating the string after it's posted.
I really love var_export(). If you like copy/paste-able code, try:
echo '<pre>' . var_export($data, true) . '</pre>';
Or even something like this for color syntax highlighting:
highlight_string("<?php\n\$data =\n" . var_export($data, true) . ";\n?>");
Reusable function:
function highlight_array($array, $name = 'var') {
highlight_string("<?php\n\$$name =\n" . var_export($array, true) . ";\n?>");
}
You can do the same with print_r(). For var_dump() you would just need to add the <pre> tags:
echo '<pre>';
var_dump($data);
echo '</pre>';
Try xdebug extension for php.
Example:
<?php var_dump($_SERVER); ?>
Outputs:
Use preformatted HTML element
echo '<pre>';
var_dump($data);
echo '</pre>';
I have make an addition to #AbraCadaver answers.
I have included a javascript script which will delete php starting and closing tag.
We will have clean more pretty dump.
May be somebody like this too.
function dd($data){
highlight_string("<?php\n " . var_export($data, true) . "?>");
echo '<script>document.getElementsByTagName("code")[0].getElementsByTagName("span")[1].remove() ;document.getElementsByTagName("code")[0].getElementsByTagName("span")[document.getElementsByTagName("code")[0].getElementsByTagName("span").length - 1].remove() ; </script>';
die();
}
Result before:
Result After:
Now we don't have php starting and closing tag
I don't seem to have enough rep to close this as a duplicate, but it is one if someone else can do that. I posted the same thing over at A more pretty/informative Var_dump alternative in PHP? but for the sake of saving time, I'll copy/paste it here too:
I had to add another answer here because I didn't really want to go through the steps in the other solutions. It is extremely simple and requires no extensions, includes etc and is what I prefer. It's very easy and very fast.
First just json_encode the variable in question:
echo json_encode($theResult);
Copy the result you get into the JSON Editor at http://jsoneditoronline.org/ just copy it into the left side pane, click Copy > and it pretty prints the JSON in a really nice tree format.
To each their own, but hopefully this helps some others have one more nice option! :)
Here's an alternative, actively maintained open source var_dump on steroids:
https://github.com/php-sage/sage
It works with zero set up and is more useable than Xdebug's var_dump and symfony/var-dumper.
Example which bypasses the dumped object size limit on the fly with Kint:
require 'sage.phar';
+d( $variable ); // append `+` to the dump call
Here's a screenshot:
If it's "all smushed together" you can often give the ol' "view source code" a try. Sometimes the dumps, messages and exceptions seem like they're just one long string when it turns out that the line breaks simply don't show. Especially XML trees.
Alternatively, I've once created a small little tool called InteractiveVarDump for this very purpose. It certainly has its limits but it can also be very convenient sometimes. Even though it was designed with PHP 5 in mind.
The best what and easiest way to get nice var_dump is use xDebug (must have for any php dev)
Debian way install
In console: apt-get install php-xdebug
after that you should open php.ini (depends on which stack you use) for it's /etc/php/7.0/fpm/php.ini
Search for display_errors
set same -> display_errors = On
Check html_errors in same file a little bit below, it's also must be On
Save and exit
After open /etc/php/7.0/fpm/conf.d/20-xdebug.ini
And add to the end:
```
xdebug.cli_color=1
```
Save and exit.
A lot other available option and documentation for xdebug can be founded here.
https://xdebug.org/docs/
Good luck and Have Fun !!!
Result
You could use this one debugVar() instead of var_dump()
Check out: https://github.com/E1NSER/php-debug-function
Here is my function to have a pretty var_dump. Combined with Xdebug, it helps a lot to have a better view of what we are dumping.
I improved a bit the display of Xdebug (give some space around, separator between values, wrap long variables, etc).
When you call the function, you can set a title, a background, a text color to distinguish all your var_dump in a page.
Or not ;)
/**
* Pretty var_dump
* Possibility to set a title, a background-color and a text color
*/
function dump($data, $title="", $background="#EEEEEE", $color="#000000"){
//=== Style
echo "
<style>
/* Styling pre tag */
pre {
padding:10px 20px;
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;
}
/* ===========================
== To use with XDEBUG
=========================== */
/* Source file */
pre small:nth-child(1) {
font-weight: bold;
font-size: 14px;
color: #CC0000;
}
pre small:nth-child(1)::after {
content: '';
position: relative;
width: 100%;
height: 20px;
left: 0;
display: block;
clear: both;
}
/* Separator */
pre i::after{
content: '';
position: relative;
width: 100%;
height: 15px;
left: 0;
display: block;
clear: both;
border-bottom: 1px solid grey;
}
</style>
";
//=== Content
echo "<pre style='background:$background; color:$color; padding:10px 20px; border:2px inset $color'>";
echo "<h2>$title</h2>";
var_dump($data);
echo "</pre>";
}
function var_view($var)
{
ini_set("highlight.keyword", "#a50000; font-weight: bolder");
ini_set("highlight.string", "#5825b6; font-weight: lighter; ");
ob_start();
highlight_string("<?php\n" . var_export($var, true) . "?>");
$highlighted_output = ob_get_clean();
$highlighted_output = str_replace( ["<?php","?>"] , '', $highlighted_output );
echo $highlighted_output;
die();
}
There is a Symfony package for this: https://symfony.com/doc/current/components/var_dumper.html.
Here is a function I made for showing arrays in a nice way:
function nicevar($var,$title=''){
if(is_array($var)){
$table = '<table>';
if($title){
$table .= '<tr><th colspan="20">'.$title.'</th></tr>';
}
foreach($var as $k => $v){
$table .= '<tr>';
$table .= '<td><b>'.$k.'</b></td>';
$table .= '<td>';
if(is_array($v)){
$table .= nicevar($v);
}else{
$table .= $v;
}
$table .= '</td>';
$table .= '</tr>';
}
$table .= '</table>';
}else{
$table = $var;
}
return $table;
}
usage:
echo nicevar($_SESSION['debug'],'Structure of debug');
use this styling to make it nice:
<style>
body {
padding: 30px;
}
table {
margin: 5px;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th {
background-color: #9fff96;
}
th, td {
padding: 2px;
border-spacing: 2px;
}
</style>
in CI4, it's simpler to make the output prettier:
dd($this->request);
here is the result
I wrote a function (debug_display) which can print, arrays, objects, and file info in pretty way.
<?php
function debug_display($var,$show = false) {
if($show) { $dis = 'block'; }else { $dis = 'none'; }
ob_start();
echo '<div style="display:'.$dis.';text-align:left; direction:ltr;"><b>Idea Debug Method : </b>
<pre>';
if(is_bool($var)) {
echo $var === TRUE ? 'Boolean(TRUE)' : 'Boolean(FALSE)';
}else {
if(FALSE == empty($var) && $var !== NULL && $var != '0') {
if(is_array($var)) {
echo "Number of Indexes: " . count($var) . "\n";
print_r($var);
} elseif(is_object($var)) {
print_r($var);
} elseif(#is_file($var)){
$stat = stat($var);
$perm = substr(sprintf('%o',$stat['mode']), -4);
$accesstime = gmdate('Y/m/d H:i:s', $stat['atime']);
$modification = gmdate('Y/m/d H:i:s', $stat['mtime']);
$change = gmdate('Y/m/d H:i:s', $stat['ctime']);
echo "
file path : $var
file size : {$stat['size']} Byte
device number : {$stat['dev']}
permission : {$perm}
last access time was : {$accesstime}
last modified time was : {$modification}
last change time was : {$change}
";
}elseif(is_string($var)) {
print_r(htmlentities(str_replace("\t", ' ', $var)));
} else {
print_r($var);
}
}else {
echo 'Undefined';
}
}
echo '</pre>
</div>';
$output = ob_get_contents();
ob_end_clean();
echo $output;
unset($output);
}
Use
echo nl2br(var_dump());
This should work ^^

Embedding PHP in CSS

I'm trying to create a variable background, where the image changes based on the time of day. This code I have USED to work, but I did something somewhere along the line and didn't notice that the functionality had broken. Can someone explain to me why this doesn't work?
<html>
<?php
function day()
{
if ( $hour >= 6 && $hour <= 18 )
{
return 1;
} else { return 0; }
}
?>
<style type="text/css">
body
{
background-image: url('<?php echo (day() ? 'images/day_sheep.jpg'
: 'images/night_sheep.jpg'); ?>');
background-position: 50% 50%;
background-repeat: no-repeat;
background-color: silver
}
a {text-decoration:none;}
a:link {color:#ff0000;}
a:visited {color:#0000FF;}
a:hover {text-decoration:underline;}
</style>
</html>
Inside your function day(), $hour is unset. It will be treated as 0 in a numerical context, and if you enable reporting of notices, you will see notices warning you of an unset variable. Did it used to be a global variable? Did you remove code that set its value or declared it as global?
Edit: Also, on a point of style, I feel it would look neater to have an external CSS file like this:
body {
background-position: 50% 50%;
background-repeat: no-repeat;
background-color: silver
}
body.day {
background-image: url('images/day_sheep.jpg');
}
body.night {
background-image: url('images/night_sheep.jpg');
}
and then you can get rid of the CSS section of your php script, but include the above CSS file, and you need only have the following:
<body class="<?php echo day() ? 'day' : 'night'; ?>">
You never declare what $hour is.
<html>
<?php
function day()
{
$hour = date('G');
if ( $hour >= 6 && $hour <= 18 )
{
return 1;
} else { return 0; }
}
?>
... snip ...

Categories