How to quickly check what variables exist from a bunch of vars? - php

If you have 10 variables that are sometimes set, other times unset, is there a quick way to echo the ones that exist without throwing an exception? These vars come from user input.
I would currently write it as
if ($var_1 != NULL) { echo $var_1; }
if ($var_2 != NULL) { echo $var_2; }
if ($var_3 != NULL) { echo $var_3; }
if ($var_other_1 != NULL) { echo $var_other_1 ; }
if ($var_other_2 != NULL) { echo $var_other_2 ; }
etc.. But is there a more quicker way?

compact function will help you

Check this function: http://php.net/manual/en/function.get-defined-vars.php
You can do something like this:
<?php
$vararr = get_defined_vars();
foreach ($vararr as $name => $value) {
echo "{$name}: {$value}<br>\n";
}

Here's another option using variable variables and a list of the variables you want to examine:
foreach( array("var_1", "var_2") as $var )
{
if( isset($$var) )
{
echo $$var;
}
}

Related

php Function echo's wrong string

I'm fairly new to PHP so forgive me if this function is badly done.
I have a function:
function socialLink($sm_type = NULL) {
if ($sm_type = 'twitter') {
echo 'https://www.twitter.com';
} else {
echo 'https://www.facebook.com';
}
}
In my code when I call the function socialLink('facebook'); it echo's the Twitter URL.
Surely it should echo the Facebook URL since $sm_type would be equal to 'facebook' not twitter ?
Any help would be appreciated.
Set your if condition with this,
function socialLink($sm_type = NULL) {
if ($sm_type == 'twitter') {
echo 'https://www.twitter.com';
} else {
echo 'https://www.facebook.com';
}
}
See this.
function socialLink($sm_type = NULL) {
if ($sm_type == 'twitter') {
echo 'https://www.twitter.com';
} else {
echo 'https://www.facebook.com';
}
}
NOTE: Single = use to assign the value and = = use to compare values
Different's Between = , = = , = = =
= operator Used to just assign the value.
= = operator Used to just compares the values not datatype
= = = operator Used to Compare the values as well as datatype.
Your if statement does not use a comparison operator, it is an assignment (=). For a comparison, please use "==".
if ($sm_type == 'twitter') {
echo 'https://www.twitter.com';
} else {
echo 'https://www.facebook.com';
}
if ($sm_type == 'twitter') {
echo 'https://www.twitter.com';
} else {
echo 'https://www.facebook.com';
}
In php == is use for string comparison so, In this case you can't used = for that, simple :)

How to find where a special Smarty variable is declared in PrestaShop?

I using prestashop 1.6 and I have some variable in my index.tpl like as $aslist that I Don't know where this variable is defined or assigned!
I need to find this variable and do some change over that.
anybody know how can I find a solution that show where smarty variables assigned ?
I need to a address file like as:
$aslist assigned in .\www\controllers\front\CmsController.php - (line 58 )
You can add this function to config/config.inc.php
function log_smarty_assign($var_name)
{
$smarty_var_filter = 'aslist';
if ($var_name == $smarty_var_filter)
{
$log = '';
$trace = debug_backtrace(false);
if (isset($trace[1]))
{
$log .= 'Variable '.$var_name.' assigned in ';
$log .= $trace[1]['file'].' #'.$trace[1]['line'];
echo "<pre>$log</pre>";
}
}
}
Edit: $trace[1] should be used instead of $trace[2]
And then search for the smarty assign method and modify it to something like this:
I found it in /tools/smarty/sysplugins/smarty_internal_data.php
public function assign($tpl_var, $value = null, $nocache = false)
{
if (is_array($tpl_var)) {
foreach ($tpl_var as $_key => $_val) {
if ($_key != '') {
$this->tpl_vars[$_key] = new Smarty_variable($_val, $nocache);
//log the assignment
log_smarty_assign($_key);
}
}
} else {
if ($tpl_var != '') {
$this->tpl_vars[$tpl_var] = new Smarty_variable($value, $nocache);
//log the assignment
log_smarty_assign($tpl_var);
}
}
return $this;
}
Output example:
Variable product assigned in ...\classes\controller\Controller.php #180

Checking for undefined variables in a function php

So I've been trying to devise a function that will echo a session variable only if it is set, so that it wont create the 'Notice' about an undefined variable. I am aware that one could use:
if(isset($_SESSION['i'])){ echo $_SESSION['i'];}
But it starts to get a bit messy when there are loads (As you may have guessed, it's for bringing data back into a form ... For whatever reason). Some of my values are also only required to be echoed back if it equals something, echo something else which makes it even more messy:
if(isset($_SESSION['i'])){if($_SESSION['i']=='value'){ echo 'Something';}}
So to try and be lazy, and tidy things up, I have tried making these functions:
function ifsetecho($variable) {
if(!empty($variable)) {
echo $variable;
}
}
function ifseteqecho($variable,$eq,$output) {
if(isset($variable)) {
if($variable==$eq) {
echo $output;
}
}
}
Which wont work, because for it to go through the function, the variable has to be declared ...
Has anyone found a way to make something similar to this work?
maybe you can achieve this with a foreach?
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$eq,$output) {
if($variable==$eq) {
echo $output;
}
else echo $variable;
}
}
now this will all check for the same $eq, but with an array of corresponding $eq to $variables:
$equiv = array
('1'=>'foo',
'blue'=>'bar',);
you can check them all:
foreach ($_SESSION as $variable)
{function ifseteqecho($variable,$equiv) {
if(isset($equiv[$variable])) {
echo $equiv[$variable];
}
else {
echo $variable;
}
}
}
Something like this?, you could extend it to fit your precise needs...
function echoIfSet($varName, array $fromArray=null){
if(isset($fromArray)){
if(isset($fromArray[$varName])&&!empty($fromArray[$varName])){
echo $fromArray[$varName];
}
}elseif(isset($$varName)&&!empty($$varName)){
echo $$varName;
}
}
You may use variable variables:
$cat = "beautiful";
$dog = "lovely";
function ifsetecho($variable) {
global $$variable;
if(!empty($$variable)){
echo $$variable;
}
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
UPDATE: With a rather complex code I’ve managed to meet your requirements:
session_start();
$cat = "beautiful";
$dog = "lovely";
$_SESSION['person']['fname'] = "Irene";
function ifsetecho($variable){
$pattern = "/([_a-zA-Z][_a-zA-Z0-9]+)".str_repeat("(?:\\['([_a-zA-Z0-9]+)'\\])?", 6)."/";
if(preg_match($pattern, $variable, $matches)){
global ${$matches[1]};
if(empty(${$matches[1]})){
return false;
}
$plush = ${$matches[1]};
for($i = 2; $i < sizeof($matches); $i++){
if(empty($plush[$matches[$i]])){
return false;
}
$plush = $plush[$matches[$i]];
}
echo $plush;
return true;
}
return false;
}
ifsetecho("cat");
echo "<br/>";
ifsetecho("dog");
echo "<br/>";
ifsetecho("elephant");
echo "<br/>";
ifsetecho("_SESSION['person']['fname']");
echo "<br/>";
ifsetecho("_SESSION['person']['uname']");
echo "<br/>";

how can i do first variable like second variable in php

my code is
<?php if($_SERVER['REQUEST_URI'] == "/scripts/script1.php")
{
echo 'yes';
}
else
{
echo 'no';
}
some time my URL come like
www.example.com/scripts/script1.php?var1=value1&var2=value2
How can do that with PHP
URL like function....
Make use of strpos in PHP
<?php
if(strpos($_SERVER['REQUEST_URI'],"/scripts/script1.php")!==false)
{
echo 'yes';
}
else
{
echo 'no';
}
A slight variation on Shankar's answer
$result = "no";
if( strpos( $_SERVER[ "REQUEST_URI" ], "/scripts/script1.php" ) !== false ) {
$result = "yes";
}
By setting the default value for the variable, you can make your code more concise and improve readability.

Creating elegant if statements

I have the following set of if statements:
<?php
if (!empty($sn1link) && !empty($sn1)) {
echo('<button class="lbutton-content">'.$sn1.'</button>');
}
if (!empty($sn2link) && !empty($sn2)) {
echo('<button class="lbutton-content">'.$sn2.'</button>');
}
if (!empty($sn3link) && !empty($sn3)) {
echo('<button class="lbutton-content">'.$sn3.'</button>');
}
if (!empty($sn4link) && !empty($sn4)) {
echo('<button class="lbutton-content">'.$sn4.'</button>');
}
if (!empty($sn5link) && !empty($sn5)) {
echo('<button class="lbutton-content">'.$sn5.'</button>');
?>
I would like a more elegant way of combining these if statements. I've tried else if but obviously this would only display the first if statement that returns TRUE whereas I'd like to return every TRUE statement. I don't think a switch would work either.
Why not iterate and use arrays?
foreach($sn_array as $link => $text):
if(!empty($link) && !empty($text)) echo ...;
endforeach;
Perhaps a for loop with variable variables:
<?php
for ($i = 1; $i <= 5; $i++) {
$link = 'sn'.$i.'link';
$button = 'sn'.$i;
if (!empty($$link) && !empty($$button)) {
echo('<button class="lbutton-content">'.$$button.'</button>');
}
}
you should make it a loop, where the values are in an array. then only one if, and one echo statement are needed to accomplish the same thing.
$snList = array($sn1 => $sn1Link, $sn2 => $sn2Link, $sn3 => $sn3Link);
foreach ($snList as $name => $link) {
echo('<button class="lbutton-content">'.$name.'</button>');
}
you don't even need the if statement, because if the values don't exist, you simply don't add them to the $snList array in the first place.
$snList = array();
$snList[$key] = $value;
I'm not sure how much more elegant this would be but you could use a function like:
function getButtonContent($link, $content) {
if (!empty($link) && !empty($content)) {
echo('<button class="lbutton-content">'.$content.'</button>');
}
}
getButtonContent($sn1link, $sn1);
getButtonContent($sn2link, $sn2);
getButtonContent($sn3link, $sn3);
etc....
If you have this in more than on place or have something similar the function approach might help.

Categories