Help with an if and else statement logic - php

The code below is just a sample of the format I have
isset($_GET['ids'])?$ids=$_GET['ids']:null;
isset($_POST['idc'])?$idc=$_POST['idc']:null;
function ShowCart()
{
$que = "SELECT
FROM
cart
LEFT OUTER JOIN ...
ON ...
LEFT OUTER JOIN... ON...
WHERE ";
$result = mysql_query($que);
while(){
if (isset($ids)) {
display something
for (){
if(){
} // end of if inside the for loop
}// end of for loop
}
elseif($idc && $ids=null) {
display something different
}
else{
display nothing has passed
}
}//end of while loop
}//end of showcart(); function
that's the formatting above I wonder why the if and elseif are not getting the isset() as the if and elseif argument.
I have debug the through the whole code and the print_r of GET and POST has values through the whole code.
print_r($_POST);
print_r($_GET);

Jona, if you'd ever bother to properly format your code, you'd see that the 'else' in question is WITHIN A FUNCTION, and you're defining $ids and $idc OUTSIDE THE FUNCTION. Remember, in PHP, global variables (except the super-globals, such as $_GET, $_POST, etc...) are not visible within functions unless you explicity define them as globals within the function.
Add global $idc, $idc; as the first line in the function definition and your if() will start working correctly.
Followup:
Your code is still hideously formatted, and very wonky. Take this:
isset($_GET['ids'])?$ids=$_GET['ids']:null;
You're using a trinary operator, but not assigning its results anywhere, and using the 'true' condition to do an assignment. This is an ugly hack. It should be written like this:
$ids = isset($_GET['ids']) ? $_GET['ids'] : null;
This way $ids will be set to null if there is no $_GET['ids']. Which brings up the fact that you're assigning a null instead of some other default value. If there really was no $_GET['ids'], then this:
$idx = $_GET['ids'];
would work identically, as PHP will automatically assign a null in situations where the right-hand-side doesn't exist. Of course, you still have to sanitize this value, since you're using it in an SQL query later on. Leaving it like this will just invite SQL injection attacks and all kinds of other abuses.
Beyond that, you're still creating $ids and $idc OUTSIDE of your ShowCart() function. As such, $ids and $idc within the function will be automatically be created with null values, since you've not declared them to be global. I think by now it's obvious you have no idea what this means, so try out this piece of code:
<?php
$var = 'Here I am!';
function showVar() {
echo "Within showVar(), var is set to: $var\n";
}
function workingShowVar() {
global $var;
echo "Within workingShowVar(), var is equal to: $var\n";
}
showVar();
workingShowVar();
If you copy/paste this code, run it, you'll see the following output:
Within showVar(), var is set to:
Within workingShowVar(), var is set to: Here I am!
Notice that both functions are identical, except for the global declaration. If you can figure out the difference, then you'll realize you need to re-write your ShowCart() function as follows:
function ShowCart() {
global $ids, $idc;
// rest of your code here
}

Well the code you've posted is sound, so it's probably a problem with the variables getting to that script in the first place. Are you sure those variables are defined in the GET string?
Dump out the contents of it to make sure:
print_r($_GET);

Try this:
$ids= isset($_GET['ids'])?intval($_GET['ids']):null;
$idc= isset($_GET['idc'])?intval($_GET['idc']):null;
if (isset($ids)) {
//display something
}
elseif(isset($idc)) {
//display something different
}
else
{
//display nothing has passed
}

I tested your script above,it works as expected.Maybe you should check whether the link is correct or not.

Related

how to rewrite this php "if" statement without the deprecated "each" function?

How can I rewrite this piece of php script to not use the deprecated function 'each' anymore in the 'if' statement ?
if (list($_basic_auth_realm, $_basic_auth_header) = each($_auth_creds))
{
...
}
Many thx in adv. for you input !
V.
[EDIT]. This if statement is not in a loop. It's part of an larger block:
if (!empty($_basic_auth_header))
{
....
}
else if (!empty($_basic_auth_realm) && isset($_auth_creds[$_basic_auth_realm]))
{
....
}
else if (list($_basic_auth_realm, $_basic_auth_header) = each($_auth_creds))
{
....
}
$_basic_auth_realm, $_basic_auth_header are strings
$_auth_creds is an array
I don't really understand how this 'if' statement works. I only attempt to update the script which returns warnings when executed. It is used as a php proxy on my NAS as was written by Abdullah Arif: https://github.com/emersion/phproxy
Use your own variable to keep track of the current index in the array, rather than depending on the internal state of the array.
$auth_creds_index = 0;
...
else if (list($_basic_auth_realm, $_basic_auth_header) = $_auth_creds[$auth_creds_index++])
Each place where you currently use each($_auth_creds) should use $_auth_creds[$auth_creds_index++], they'll get successive elements of the array.
If you reassign the variable with a new array, you need to reset the variable back to 0.
You could also define a class wrapper for the array that automates all this.

There is a short way to write if(!is_null($foo) && !is_null($bar))?

So, I am writing a function that receives two arguments, and before I do anything with these variables, I want to check if they are not null.
if (!is_null($foo) && !is_null($bar)) {
/* do something */
}
The problem is that I think we are repeating code, and in some cases when the variable name is a little bit bigger, it becomes painful to write every time.
So, there is a way to shorten this code?
You can use isset which returns FALSE if variable is null. You can set there a lot of variables so code will be shorter:
if (isset($foo, $bar))
You can write your own function to check this:
function is_any_null() {
$params = func_get_args();
foreach($params as $param) {
if (is_null($param))
return true;
}
return false;
}
Now you can use it like this:
if (!is_any_null($foo, $bar)) {
/* do something */
}
is_null() checks a variable to determine if the value is NULL. It can be used in an if statement. It depends on what you would like to do in that if statement. For example, if you would like to do an echo, you can make it a bit shorter using the `elvis``operator:
echo (is_null($foo) && is_null($bar)) ?: 'The values are not null';
Or you could make it a one liner by leaving the { and } out of your code and putting everything on one line.
if (!is_null($foo) && !is_null($bar)) die("NULLLLL");

PHP take string and check if that string exists as a variable

I have an interesting situation. I am using a form that is included on multiple pages (for simplicity and to reduce duplication) and this form in some areas is populated with values from a DB. However, not all of these values will always be present. For instance, I could be doing something to the effect of:
<?php echo set_value('first_name', $first_name); ?>
and this would work fine where the values exist, but $user is not always set, since they may be typing their name in for the first time. Yes you can do isset($first_name) && $first_name inside an if statement (shorthand or regular)
I am trying to write a helper function to check if a variable isset and if it's not null. I would ideally like to do something like varIsset('first_name'), where first_name is an actual variable name $first_name and the function would take in the string, turn it into the intended variable $first_name and check if it's set and not null. If it passes the requirements, then return that variables value (in this case 'test'). If it doesn't pass the requirements, meaining it's not set or is null, then the function would return '{blank}'.
I am using CodeIgniter if that helps, will be switching to Laravel in the somewhat near future. Any help is appreciated. Here is what I've put together so far, but to no avail.
function varIsset($var = '')
{
foreach (get_defined_vars() as $val) {
if ($val == $var) {
if (isset($val) && $val) {
echo $val;
}
break;
}
}
die;
}
Here is an example usage:
<?php
if (varIsset('user_id') == 100) {
// do something
}
?>
I would use arrays and check for array keys myself (or initialize all my variables...), but for your function you could use something like:
function varIsset($var)
{
global $$var;
return isset($$var) && !empty($$var);
}
Check out the manual on variable variables. You need to use global $$var; to get around the scope problem, so it's a bit of a nasty solution. See a working example here.
Edit: If you need the value returned, you could do something like:
function valueVar($var)
{
global $$var;
return (isset($$var) && !empty($$var)) ? $$var : NULL;
}
But to be honest, using variables like that when they might or might not exist seems a bit wrong to me.
It would be a better approach to introduce a context in which you want to search, e.g.:
function varIsset($name, array $context)
{
return !empty($context[$name]);
}
The context is then populated with your database results before rendering takes place. Btw, empty() has a small caveat with the string value "0"; in those cases it might be a better approach to use this logic:
return isset($context[$name]) && strlen($name);
Try:
<?php
function varIsset($string){
global $$string;
return empty($$string) ? 0 : 1;
}
$what = 'good';
echo 'what:'.varIsset('what').'; now:'.varIsset('now');
?>

How to assign values into global array inside a function? (php)

I have a function that searches for a string inside a text file. I want to use the same function to assign all lines to an array in case I am going to replace that string. So I will read the input file only once.
I have the search function working but I do not know how to deal with the array thing.
the code is something like that (I made the code sample much simpler,so please ignore the search function that actually isn't below)
function read_ini($config_file_name,$string){
$config_file = file($config_file_name);
foreach($config_file as $line) {
return_string = trim(substr($line,0,15));
$some_global_array = $line'
}
}
echo read_ini('config.ini','database.db')
if ($replaced) {file_put_contents('config.ini', $some_global_array);}
http://php.net/parse_ini_file
I know it doesn't answer the question, but it quite possibly removes the need for even having to ask.
The deal with globals, though, is that they must be defined at the top of the function as globals, or else they're considered part of the function's scope.
function write_global() {
global $foo;
$foo = 'bar';
}
write_global();
echo $foo; // bar

Find the name of a calling var

Anyone has an idea if this is at all possible with PHP?
function foo($var) {
// the code here should output the value of the variable
// and the name the variable has when calling this function
}
$hello = "World";
foo($hello);
Would give me this output
varName = $hello
varValue = World
EDIT
Since most people here 'accuse' me of bad practices and global variables stuff i'm going to elaborate a little further on why we are looking for this behaviour.
the reason we are looking at this kind of behaviour is that we want to make assigning variables to our Views easier.
Most of the time we are doing this to assign variables to our view
$this->view->assign('products', $products);
$this->view->assign('members', $members);
While it would be easier and more readable to just be able to do the following and let the view be responsible to determining the variable name the assigned data gets in our views.
$this->view->assign($products);
$this->view->assign($members);
Short answer: impossible.
Long answer: you could dig through apd, bytekit, runkit, the Reflection API and debug_backtrace to see if any obscure combination would allow you to achieve this behavior.
However, the easiest way is to simply pass the variable name along with the actual variable, like you already do. It's short, it's easy to grasp, it's flexible when you need the variable to have a different name and it is way faster than any possible code that might be able to achieve the other desired behavior.
Keep it simple
removed irrelevant parts after OP edited the question
Regardless of my doubt that this is even possible, I think that forcing a programmer on how to name his variables is generally a bad idea. You will have to answer questions like
Why can't I name my variable $arrProducts instead of $products ?
You would also get into serious trouble if you want to put the return value of a function into the view. Imagine the following code in which (for whatever reason) the category needs to be lowercase:
$this->view->assign(strtolower($category));
This would not work with what you're planning.
My answer therefore: Stick to the 'verbose' way you're working, it is a lot easier to read and maintain.
If you can't live with that, you could still add a magic function to the view:
public function __set($name, $value) {
$this->assign($name, $value);
}
Then you can write
$this->view->product = $product;
I don't think there is any language where this is possible. That's simply not how variables work. There is a difference between a variable and the value it holds. Inside the function foo, you have the value, but the variable that held the value is not available. Instead, you have a new variable $var to hold that value.
Look at it like this: a variable is like a bucket with a name on it. The content (value) of the variable is what's inside the bucket. When you call a function, it comes with its own buckets (parameter names), and you pour the content of your bucket into those (well, the metaphor breaks down here because the value is copied and still available outside). Inside the function, there is no way to know about the bucket that used to hold the content.
What you're asking isn't possible. Even if it was, it would likely be considered bad practice as its the sort of thing that could easily get exploited.
If you're determined to achieve something like this, the closest you can get would be to pass the variable name as a string and reference it in the function from the $GLOBALS array.
eg
function this_aint_a_good_idea_really($var) {
print "Variable name: {$var}\n";
print "Variable contents: {$GLOBALS[$var]}\n";
}
$hello="World";
this_aint_a_good_idea_really('hello');
But as I say, that isn't really a good idea, nor is it very useful. (Frankly, almost any time you resort to using global variables, you're probably doing something wrong)
Its not impossible, you can find where a function was invoked from debug_backtrace() then tokenize a copy of the running script to extract the parameter expressions (what if the calling line is foo("hello $user, " . $indirect($user,5))?),
however whatever reason you have for trying to achieve this - its the wrong reason.
C.
Okay, time for some ugly hacks, but this is what I've got so far, I'll try to work on it a little later
<?php
class foo
{
//Public so we can test it later
public $bar;
function foo()
{
//Init the array
$this->bar = array();
}
function assign($__baz)
{
//Try to figure out the context
$context = debug_backtrace();
//assign the local array with the name and the value
//Alternately you can initialize the variable localy
//using $$__baz = $context[1]['object']->$__baz;
$this->bar[$__baz] = $context[1]['object']->$__baz;
}
}
//We need to have a calling context of a class in order for this to work
class a
{
function a()
{
}
function foobar()
{
$s = "testing";
$w = new foo();
//Reassign local variables to the class
foreach(get_defined_vars() as $name => $val)
{
$this->$name = $val;
}
//Assign the variable
$w->assign('s');
//test it
echo $w->bar['s'];
}
}
//Testrun
$a = new a();
$a->foobar();
impossible - the max. ammount of information you can get is what you see when dumping
debug_backtrace();
Maybe what you want to do is the other way around, a hackish solution like this works fine:
<?php
function assign($val)
{
global $$val;
echo $$val;
}
$hello = "Some value";
assign('hello');
Ouputs: Some value
What you wish to do, PHP does not intend for. There is no conventional way to accomplish this. In fact, only quite extravagant solutions are available. One that remains as close to PHP as I can think of is creating a new class.
You could call it NamedVariable, or something, and as its constructor it takes the variable name and the value. You'd initiate it as $products = new NamedVariable('products', $productData); then use it as $this->view->assign($products);. Of course, your declaration line is now quite long, you're involving yet another - and quite obscure - class into your code base, and now the assign method has to know about NamedVariable to extract both the variable name and value.
As most other members have answered, you are better off suffering through this slight lack of syntactic sugar. Mind you, another approach would be to create a script that recognizes instances of assign()'s and rewrites the source code. This would now involve some extra step before you ran your code, though, and for PHP that's silly. You might even configure your IDE to automatically populate the assign()'s. Whatever you choose, PHP natively intends no solution.
This solution uses the GLOBALS variable. To solve scope issues, the variable is passed by reference, and the value modified to be unique.
function get_var_name(&$var, $scope=FALSE) {
if($scope) $vals = $scope;
else $vals = $GLOBALS;
$old = $var;
$var = $new = 'unique'.rand().'value';
$vname = FALSE;
foreach ($vals as $key => $val) {
if($val === $new) $vname = $key;
}
$var = $old;
return $vname;
}
$testvar = "name";
echo get_var_name($testvar); // "testvar"
function testfunction() {
$var_in_function = "variable value";
return get_var_name($var_in_function, get_defined_vars());
}
echo testfunction(); // "var_in_function"
class testclass {
public $testproperty;
public function __constructor() {
$this->testproperty = "property value";
}
}
$testobj = new testclass();
echo get_var_name($testobj->testproperty, $testobj); // "testproperty"

Categories