PHP set a variables from $_GET['var'] - php

Is it possible to set a variables value from a $_GET['var'] doing somthing like this:
if( $foo = isset($_GET['foo']) ) // Or something close to this.
I.e if $_GET['foo'] is set assign it's value then and there
instead of this like I currently do
if( isset($_GET['foo']) )
$foo = $_GET['foo'];
This is ok when it's just one or two, but like me when you have 10+ $_GET's it gets ugly.

user ternary operator
$foo = isset($_GET['foo']) ? $_GET['foo'] : "";

try
$foo = !empty($_GET['foo']) ? $_GET['foo'] : null;

No, this is not possible. You can do it in shorthand with a ternary statement, but that's not a great deal less clunky.
The best you can do might be to write a function like the following:
function extractFromGet(array $keys) {
$ret = []; // empty array
foreach ($keys as $key) {
$ret[$key] = isset($_GET[$key]) ? $_GET[$key] : null;
}
return $ret;
}
You can then call it as follows:
list ($name, $email, $telephone, $address) = extractFromGet(
['name', 'email', 'telephone', 'address']
);

Related

PHP shorthand to skip a variable assignment

I am using this shorthand in a function to set a variable to NULL if it is not set. How can I simply not set it?
function createArray($rows){
$array = array();
$array['id'] = isset($rows['UnitId']) ? $rows['UnitId'] : NULL ;
}
Would this be too simple for you?
if(isset($rows['UnitId'])) {
$array['id'] = $rows['UnitId'];
}
Just don't set it in the first place
function createArray($rows){
$array = array();
if(isset($rows['UnitId'])) $array['id'] = $rows['UnitId'];
}

Ternary statement without middle expression

How to replace this :
if( $this->getInfo() ){
$value = $this->getInfo();
}else{
$value = $this->getAnotherInfo();
}
This would be nicer solution :
$value = $this->getInfo() ? $this->getInfo() : $this->getAnotherInfo();
But we repeat $this->getInfo().
Here is the fun:
$value = $this->getInfo() ? : $this->getAnotherInfo();
If it bothers you having to repeat the expression you could write a function that returns the first truthy value.
$value = which ($this->getInfo(), $this->getAnotherInfo());
function which () {
if (func_num_args()<1) return false;
foreach (func_get_args() as $s) if ($s) return $s;
return false;
}
A nasty option would be this:
if (!($value = $this->getInfo())) $value = $this->getOtherInfo();
If the assignment returns false assign the other value.
But aside from this looking disgusting, it is still repetitive, albeit in a different way.
As of PHP 5.3, you can leave out the middle part of the ternary operator and avoid the repetition:
$value = $this->getInfo() ? : $this->getOtherInfo();
Which does what you want.

Shortcut to isset() and assigning values

Is there a shortcut method to assigning $_GET['values'] to variables?
I currently do like others do:
if(isset($_GET['type'],$_GET['case'])
$type = $_GET['type'];
$case = $_GET['case'];
Is there a cleaner method to do this instead of doing like below separately.
$type = $_GET['type'];
$case = $_GET['case'];
http://docs.php.net/extract
I think you're looking for extract function.
extract($_GET); //now, all of the functions are in current symbol table
Well, with array map you can you get the case not just once, but all at once, and you can also check for isset() and empty() at the same time too.
Suppose, you have this URL: read.php?id=1&name=foo&job=student&country=Brazil
Your problem is fetching the $_GET type, and you may need to check if is it empty/isset or not right?
Well, first you create a function to iterate through it.
function checkGet($val){
return (isset($val) && !empty($val)) ? $val : null;
}
Then, you callback that function with array_map()
$check = array_map('checkGet', $_GET);
And that is it!
If you were to do var_dump($check); now, you would get get all the types, and values:
array (size=4)
'id' => string '1' (length=1)
'name' => string 'foo' (length=3)
'job' => string 'student' (length=7)
'country' => string 'Brazil' (length=6)
Meaning, after this, instad of doing:
if(isset($_GET['something']) && !empty($_GET['something']))
$var = $_GET['something'];
echo $var;
Just do:
echo $check['something']
The only one-line code I can think of, to make sure that you still do the necessary checks, is
$type = (isset($_GET['type'])) ? $_GET['type'] : 'a default value or false';
Reading comments, I understand you may want to do this:
foreach($_GET as $key=>$value) {
$$key = $value;
}
I would suggest though, to always initialize the variables you need only. The above code will result in getting unknown variables, which may actually give the user a way to manipulate your script.
Example:
index.php?ExpectedVar=1&UserDefinedVar=2
will generate the following variables in your code:
$ExpectedVar // 1 <- you wanted this one
$UserDefinedVar // 2 <- but what about this?
What if you had this script called by some other script?
Then even if you have this code at the top of your file, you may have some variables overwritten from a user defined $_GET!
Disaster case Scenario:
script1.php
<?php
$tableToDelete = "old_products";
include("script2.php");
?>
script2.php
<?php
foreach($_GET as $key=>$value) {
$$key = $value;
}
// user added &tableToDelete=users
// DROP TABLE $table
// will gloriously delete users
?>
Instead by writing a few lines with the original code I posted, you can get the variables you need at the start of your php script and use them with a clear mind.
Try like
foreach($_GET as $key=>$value) {
$get_arr[$key] = $_GET[$key];
}
print_r($get_arr);
I would do it that way, this way you make sure that it will only return TRUE or FALSE
if (!isset($_GET['type']) || empty($_GET['type'])) {
// Display error
} else {
$type = $_GET['type'];
$case = $_GET['case'];
}
Or you can do it that way as well
$type = (isset($_GET['type'])===false)?'':trim($_GET['type']);
$case = (isset($_GET['case'])===false)?'':trim($_GET['case']);
$_GET is table, so you can easy use foreach function
For example
foreach ($_GET as $key => $value) {
... = $value;
}
If you would like to create variables with $key names use variable variables
PHP Manual Variable Variables
You can do it through extract()
extract($_GET, EXTR_PREFIX_ALL, 'g');
so that
$_GET['val'] becomes $g_val
Note the third parameter: g it prepends g_ to the keys.
This (untested) class should help you:
class MyGet {
public static $myValues = array();
public static function setMyValues($keywords, $where) {
MyGet::$myValues = array();
for ($index = 0; $index < count($keywords); $index++) {
if ((!(isset($where[$keywords[$index]]))) || (empty($where[$keywords[$index]]))) {
MyGet::$myValues = array();
return false;
}
MyGet::$myValues[$keywords[$index]] = $where[$keywords[$index]];
}
}
}
You can use it like this:
if (MyGet::setMyValues(array(0 => "type", 1 => "case"), $_GET)) {
//the values are initialized
} else {
//the values are not initialized
}

How to change the variable being assigned via condition?

I want to change the variable being assigned based on condition, and I can seem to get it working.
$condition = false;
($condition !== false ? $array[1][$condition] : $array[1]) = 'Test';
In this example, if $condition isn't false, I want to assign the string "Test" to $array[1][$condition]. Otherwise, assign it to $array[1]
I can easily do this like this:
if ($condition !== false) {
$array[1][$condition] = 'Test'; }
else {
$array[1] = 'Test'; }
But due to the nature of the code this can get quite cluttered, which is why I wish for it to be an inline conditional statement.
Thanks for any help!
$condition = false;
$array[1][$condition] = ($condition !== false ? 'Test' : $array[1]);
$condition !== false ? $array[1][$condition] = "Test" : $array[1] = "Test";
The result of the ternary operator is not a reference, so you can't use it as the left-hand side of an assignment.
You might be able to use variable variables and references, but this might just add complexity without providing any real benefit.
Something like this:
$a =& $array[1];
$b =& $array[1][$condition];
$var = ($condition !== false ? 'b' : 'a');
$$var = 'Test';

passing variable names as string

I'm trying to perform the same function dosomething() to multiple variables $lastsum $avatar $angels $city $square in PHP.
$lastsum->dosomething();
$avatar->dosomething();
$angels->dosomething();
$city->dosomething();
$square->dosomething();
Is there a way to make this code cleaner by listing the names of the variables in a string array and perform the function with a for loop. I'm looking for something like this. Does anyone know the right way to do this in PHP?
$all = ['lastsum' , 'avatar', 'angels' , 'city' , 'square'];
foreach (....){
$(nameofvariable)->dosomething();
}
What's wrong with
$all = array($lastsum , $avatar, $angels, $city, $square);
foreach (....){
$variable->dosomething();
}
To achieve exactly what you're looking for, use variable variables
$all = array('lastsum' , 'avatar', 'angels' , 'city' , 'square');
foreach ($all as $x) {
$$x->dosomething();
}
Many people consider this to be bad style though.
Not an elegant solution. However, you could make use of eval():
$all = array( 'lastsum' , 'avatar', 'angels', 'city', 'square' );
foreach ( $all as $var ) {
$code = "\$${var}->dosomething();";
eval($code);
}
Otherwise, store the objects in an array:
$all = array( $lastsum , $avatar, $angels, $city, $square );
foreach ( $all as $obj ) {
$obj->dosomething();
}
If you want to use variables variables, it would be more like this:
function dosomething(&$var) {
$var .= 'bar';
}
$a = 'foo';
$b = 'bar';
$vars = array('a', 'b');
foreach ($vars as $var) {
dosomething($$var);
}
var_dump($a); // foobar
var_dump($b); // barbar
If $a is an object, then you can do $$var->dosomething().
EDIT: NOTE: In most cases, if you have to use variables variables, you may want to consider using a proper data structure instead, like an array.
Another alternative:
$all = array('lastsum' , 'avatar', 'angels' , 'city' , 'square');
foreach ($all as $x) {
$GLOBALS[$x]->dosomething();
}
Not sure if you could do method calls from the GLOBALS superglobal, but you could most likely access static properties/functions.

Categories