Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
<br />↵<b>Parse error</b>: syntax error, unexpected ':' in <b>.../ajax.php</b> on line <b>87</b>
LINE 87: $conditions = ($this->input->post()) ? : array('tutor'=>$this->session->userdata('user_id'));
line 87 works fine on localhost, but when I use godaddy I get that error. Is there something I need to set in php.ini or something to get Ternary operators to work?
Thanks!
The ternary operator (as the name suggests) usually expects 3 arguments
$var = $expr ? $trueValue : $falseValue;
With PHP5.3 its allowed to omit $trueValue. In this case its $expr is used for it
$var = $expr ? : $falseValue;
// same as
$var = $expr ? $expr : $falseValue;
You probably don't have PHP5.3 on your server. As you can see in my example its quite easy to fix this and make it ready for pre-5.3
$conditions = ($this->input->post())
? ($this->input->post())
: array('tutor'=>$this->session->userdata('user_id'));
The syntax ? : you are using is PHP 5.3 only.
Set a default value:
$conditions = ($this->input->post()) ? $this->input->post() : array('tutor'=>$this->session->userdata('user_id'));
The accepted answer is correct, but misses one important point:
$x = $a ? : $b; // valid in PHP 5.3
should indeed be replaced with
$x = $a ? $a : $b; // valid in older versions of PHP
However, when you're dealing with functions, not variables, be aware of side-effects:
$conditions = ($this->input->post())
? ($this->input->post())
: array('tutor'=>$this->session->userdata('user_id'));
In the above case, if $this->input->post()returns a truthy value, the function will be executed again, which may not be what you want. You can see this more clearly by expanding the ternary operator to its full form:
if ($this->input->post()) {
$conditions = $this->input->post();
} else {
$conditions = array('tutor' => $this->session->userdata('user_id'));
}
You can see that the function is executed on lines one and two above. If you don't want that, try this instead:
if (!$conditions = $this->input->post()) {
// Single equal sign in an if condition: make assignment, and check
// whether the result is truthy.
$conditions = array('tutor' => $this->session->userdata('user_id'));
}
This is a fairly common pattern in my own code. This will execute the function $this->input->post() only once. If the result is truthy, that result is stored in $conditions. If the result is not truthy, the code inside the if condition is run. This assigns the fallback value to $conditions. The benefit is that, in either case, $this->input->post() is run only once.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
PHP Code so far.
echo $sender = isset($_GET['s']) ? $_GET['s'] : "null";
echo $receiver = isset($_GET['r']) ? $_GET['r'] : "null";
echo $timestamp = isset($_GET['t']) ? $_GET['t'] : "0";
echo "<br/>";
echo $sTotalItems = isset($_GET['si']) ? intval($_GET['si']) : 0;
echo $rTotalItems = isset($_GET['ri']) ? intval($_GET['ri']) : 0;
echo "<br/>";
for ($i = 0; $i < $sTotalItems; $i++) {
echo $input = isset($_GET['si'+$i]) ? urldecode($_GET['si'+$i]) : "null";
if ($input == "null")
continue;
$input = explode(":", $input);
var_dump($input);
}
What I'm trying to do is dynamically grab a GET Variable. I'm sending multiple GET requests, and they all contain basically the same data, just small differences. - My question is simple though. This doesn't work like I'm thinkin it should in my mind.
$_GET['si'+$i];
In my mind, this should turn into..
$_GET['si1'];
Can this be done? Or am I going to have to figure out another way to do this?
What this is doing.. is I'm sending multiple requests.. in the following order basically..
http://dummy.com/integrate.php?s=me&r=you&t=3425&si=1&ri=2&si0=item:1:2&ri0=item:2:1&ri1=item:3:4
I'm trying to make it dynamically possible, to send more than one "item," in which there is an identifier telling the system, how many items there are for each sender, and receiver. Then a loop goes through each sender & receivers' items, and then separates the item, into 3 values. the name, the id, and the amount. The problem, is the code, isn't grabbing the item at all. Am I correct, to assume, you can't use the $_GET method, and a variable together?
Yes you can use dynamic variables along with $_GET, the only problem is use . (period) for concatenation not +.
PHP is loosely typed, so yes, you can "add" a number to a string and the number will be converted to its string representation for you. You use the concatenation operator (.) to do that, not the addition operator (+). Use $_GET['si'.$i].
The other answers show how to do what you are trying, however it's better to just use arrays.
Use item[]=something&item[]=else or even item[1]=something&item[2]=else.
Then you can access $_GET['item'][0] or $_GET['item'][1], etc.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am a beginner in php , and i want make a test with GET .
I want display , for example "ok" on my php page if my id parameter is 1 but i have always 1 when i change the id parameter to another value .
Details :
when i make this url :
http://localhost:81/test/testajax.php?id=2
expected result :
not ok
obtained result :
ok
testajax.php
<?php
if($_GET["id"] = 1)
{
die('ok');
}
else
{
die('not ok');
}
?>
One equal sign (=) sets the value of a variable. $foo = "bar"; would set $foo to store bar.
You want to use two equal signs (==), which is a comparison operator. ($foo == "bar") would check to see if $foo is equal to bar.
You can check the different types of operators at http://php.net/manual/en/language.operators.php
May be you should go through this basics before you start.
you should put two equal signs to compare.
if($_GET["id"]==1)
correct code:
<?php
if($_GET["id"] == 1)
{
die('ok');
}
else
{
die('not ok');
}
?>
As you are setting the variable, the if statement is always equating to true
Just thought it was worth Noting this as that is the logical reason for your issue
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Hey everyone I have this one line of code, and I was thinking about something, is this considered a legal assignment of a variable or will it cause errors. Furthermore is it okay to use exit() statements like this, or am I just terrible at coding somedays? Also if there is a duplicate question like this, please point me in the right direction that would be fanastic!
list($foo, $bar) ? generateValues($data) : exit("Unable to obtain useful information);
The list() you are using will assign $foo and $bar values if you use it like so:
list($foo,$bar) = array('fooValue', 'barValue');
so to properly use it in a tertiary statement would be like so:
list($foo, $bar) = (conditional) ? generateValues($data) : exit('...');
the exit will fire if the conditional is false, otherwise the array generated by generateValues() will be returned by the assignment, and list() will assign the values respectively.
Documentation.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I have a little problem with "short if" in Php.
isset($this->sets[$this->value])?$this->sets[$this->value]:$this->value
this drops notices. It looks the $this->sets[$this->value] runs even when it doesnt exists. If I do:
if (!isset($this->sets[$this->value]))
{
$this->sets[$this->value] = '';
}
it does solve the problem, but then I dont understand something....
EDIT: I refactored:
if (isset($this->sets[$this->value]))
{
$value = $this->sets[$this->value];
}
else
{
$value = $this->value;
}
return $value;
and it works, dunno why....
return 'something'.isset($this->sets[$this->value])?$this->sets[$this->value]:$this->value;
'something'.isset($this->sets[$this->value]) always evaluates to true. You'll need to group the ternary operator expression:
return 'something' . (isset($this->sets[$this->value]) ? $this->sets[$this->value] : $this->value);
And that's why you always post a complete example in your question, not just a subset!
It is not true that both operands are evaluated. Try this to see:
true?print('1'):print('2');
Only the '1' prints.
The issue is that your first line of code does not do anything in and of itself. You don't assign the result of the expression to anything, you don't use it anywhere, I would not be suprised if zend just discards it.
In your second example, you explicitly create an array element if it does not already exist. If you wanted to do the same thing with the ternary operator, you could do
isset($this->sets[$this->value])?null:($this->sets[$this->value]='');
I do not know why you would want to, but it would achieve the same thing as you did in your second example.
Your refactored example can be accomplished using the ternary operator as:
return isset($this->sets[$this->value])?$this->sets[$this->value]:$this->value;
This is a typical usage of the ternary operator
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
In some examples of PHP, I see people assign things to shorthand variables, and then use the shorthand variables instead. Is this common practice? Is this good practice?
$name = $_POST['name'];
and then they use they use $name down here to echo it or use it as a function parameter.
Another example is:
DEFINE('DB_USER', 'username');
mysqli_connect(DB_USER.......);
Pros:
Shorthand variables can be easier to type and remember.
A shorthand variable might allow an expensive operation to be done once instead of repeated many times. But beware of premature optimization! Most of the time this sort of optimization would be premature.
A shorthand variable can be used to make a copy that can be changed without modifying the original variable.
In some languages, a shorthand variable can be used to make a copy that is guaranteed to persist even if the the original variable is modified.
Cons:
Indiscriminate use of shorthand variables can result in multiple names for the same values.
In some languages and situations, a shorthand variable will make an unnecessary copy, using additional resources.
I have been doing php professionally for about 5 years now.
Usually when getting post variables it is a good idea, but even more common is to wrap it in an isset ternary if statement:
$name = isset($_POST['name']) ? $_POST['name'] : false;
This way if the variable isn't passed then you don't get an undefined variable warning.
Further, it saves you having to type $_POST every time, and it helps encapsulate the code a bit better.
The most important thing when writing code is writing readable code, not just for others but also for yourself. We do this all the time, i.e. abstracting and applying oo methods of programming.
So predefining the variables we'll be using and setting defaults makes perfect sense.
I would do something like this...
class ValueTooLong extends Exception {}
function R($param, $default=null, $type='string', $max_length=null) {
if(!isset($_REQUEST[$param]))
return $default;
$r = $_REQUEST[$param];
if($max_length && strlen($r) > $max_length)
throw new ValueTooLong('Length of '.$param.' was '.strlen($r).'. Max length is: '.$max_length);
if($type === 'bool' || $type === 'boolean') {
if($r === 'false' || $r === 'no')
return false;
return !empty($r);
}
settype($r, $type);
return $r;
}
# Which allows me do do this:
$name = R('name');
# or:
$count = R('count', 1, 'int');
EDIT: Function now takes a max_length parameter (as suggested by comment) and throws an exception if value of request parameter is too long