This question already has answers here:
Weird PHP error: 'Can't use function return value in write context'
(12 answers)
Closed 9 years ago.
EDIT FOR THE ADMINS: IT IS NOT THE SAME QUESTION AS THE ONE ALREADY ASKED, SINCE THE ORIGIN OF THE ISSUE IS DIFFERENT!!!
I am trying to display the current language selected, which is saved in the sessions table.
What I did first was the simple statement:
<?php echo $this->session->userdata("language"); ?>
which works quite well. The problem here is, that the language is saved into the session table in English and lower case, means: "english", "german", "spanish", etc
I then tried to resolve this using an if statement as follows:
<?php if ($this->session->userdata("language") = spanish) { echo 'Español'; } else if ($this->session->userdata("language") = english) { echo 'English'; } else echo 'Deutsch'; ?>
unfortunately, this returns:
Fatal error: Can't use method return value in write context in
/home/.../.../.../app/views/header.php on line 270
Any hint on what I am doing wrong? Thanks for your quick help ;)
You need to use a comparison operator == (I'm sure your = is just the usual common typo), since you can't assign a value (write) to the $this->session->userdata('anything') (method return), i.e.
Can't use method return value in write context
<?php if ($this->session->userdata("language") == 'spanish') {
echo 'Español';
}
elseif($this->session->userdata("language") == 'english') {
echo 'English';
}
else echo 'Deutsch';
?>
== operator and quoted strings should solve it:
<?php
if ($this->session->userdata("language") == 'spanish') { echo 'Español'; }
else if ($this->session->userdata("language") == 'english') { echo 'English'; }
else echo 'Deutsch';
?>
Make use of a SWITCH Statement to achieve this [Code will really look readable]
<?php
$language=$this->session->userdata("language");
switch($language)
{
case "spanish":
echo 'Español';
break;
case "english":
echo 'English';
break;
//.... goes on
}
To compare two things you should be using the == Operator. Also string values should be wrapped into quotes "myStringValue".
Related
I have a question about php (wordpress) I have a plugin(buddypress) with function bp_the_profile_field_name();
when i use
echo bp_the_profile_field_name();
It's return "Tags"
But..
if (bp_the_profile_field_name() == "Tags"){
echo "Yes, it's working";
} else {
echo "Oh no..";
}
?>
its return "Oh no.."
When i try equal to string "Tags" dosent't match.
Why? Please help
When googling to the source of the bp_the_profile_field_name function I found this source:
function bp_the_profile_field_name() {
echo bp_get_the_profile_field_name();
}
Here we can see that the the function uses echo to show the value.
If you want to get the value to compare it with something else you'll need to use a other function which will return the value.
Below the mentioned page in the 'related' part this function is mentioned:
bp_get_the_profile_field_name
Returns the XProfile field name.
Note the _get_ insteaf off _the_
Which returns a string. Source can be found here.
So your code should become:
if (bp_get_the_profile_field_name() == "Tags"){
echo "Yes, it's working";
} else {
echo "Oh no..";
}
According to documentation (https://www.buddyboss.com/resources/reference/functions/bp_the_profile_field_name/) bp_the_profile_field_name() echoes output.
If you want to compare the output of this function you need a return, not echo.
You have 2 options:
Use bp_get_the_profile_field_name() instead of bp_the_profile_field_name() in your if statement
Edit bp_the_profile_field_name() to output the result instead of echoing it.
This question already has answers here:
The 3 different equals
(5 answers)
Closed 5 years ago.
I'm currently experimenting with PHP GET Requests, But stuck with this.
Please remember i haven't really experimented with this.
So it's rather now to me,
To the point..
I'm trying to return an invalid argument message if the user does not specify
one of the following arguments
Been tinkering with this for quite a bit,
But unable to really figure it out.
?param=first or ?param=second
But it returns it returns the valid parameter message anyway.
Any suggestions to this?
I'll drop my code below!
<?php
$param = $_GET['param'];
if (empty($_GET['param']))
{
print('<h2>Parameter param is not set!<h2>');
print '<br>';
print('<h5><font color="red">Proper usage: http://localhost/zoek.php/?param=first</font></h5>'); //first
print('<h5><font color="red">Or second http://localhost/zoek.php/?param=second</font></h5>'); //second
die();
}
?>
<?php
if ($param == 'first')
{
print('Do something when url = http://localhost/zoek.php/?focus=first');
//do more stuff
}
else if ($param = 'second')
{
print('Do something when url = http://localhost/zoek.php/?focus=second');
//do more stuff.
}
//attempt to return error message when parameter $param is not first or second
else
{
print('The by you specified argument '. $_GET['param'] .' is invalid.');
die();
}
?>
The problem is with this line:
else if ($param = 'second')
It should be == instead of =.
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 8 years ago.
Improve this question
I have an array like this
$cars=array("Volvo","BMW","Toyota");
and I use this function to verify if the car BMW is in the array
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++) {
echo $cars[$x];
echo "<br>";
if($cars[$x]="Mercedes"){
echo "OK ";
}
else
{
echo "NO ";
}
}
?>
But the result is:
Volvo
OK BMW
OK Toyota
OK
How the result is this?
Your problem is down to this line:
if($cars[$x]="Mercedes")
You are not comparing but assigning instead. You need to use a double-equal for compmarison: == - for your purpose.
However a much better solution would be to use in_array function:
if(in_array("Mercedes", $cars)) {
echo "OK";
}
Use [in_array()][1] to check whether a value is found in an array.
I would use the in_array() function http://php.net/manual/en/function.in-array.php
The direct answer to your question is because = and == are not the same. It should be if( $cars[$x] == "Mercedes")
However you can avoid the problem entirely by using the appropriate built-in functions:
if( in_array("Mercedes",$cars)) echo "Oh look a fancy car!";
I would suggest you this function:
http://www.w3schools.com/php/func_array_in_array.asp
Use in_array() to check whether a value is found in an array. Like so:
$inArray = in_array("BMW", $cars);
if ($inArray)
echo 'OK';
Your main problem is that you're not using the comparison operator ==, but instead, you are using = which is the operator used to assign variables, so if($cars[$x]="Mercedes") is always evaluating to true and therefore you're seeing OK everytime. So you have to use == instead
On the other hand, what you want may be accomplished in a better way, using in_array()
$cars=array("Volvo","BMW","Toyota");
if(in_array('Mercedes', $cars)) echo 'OK';
However, if you're also interested in finding out how many Mercedes' are in there, you need to do the following
$cars=array("Volvo","BMW","Toyota");
$cars = array_count_values($cars);
if(isset($cars['Mercedes'])) {
echo 'There are '.$cars['Mercedes'].' mercedes in the array';
} else {
echo 'There are no mercedes in the array.';
}
First, you are looking to every elements in your array:
for each element:
you display the name with echo $cars[$x];
return to a new line with <br>
if it is a "Mercedes" you display "OK"; if it's not "NO"
BUT in fact you don't test if it is a "Mercedes" because you doesn't use a comparator sign (==) but an assignement sign (=) so it is always true.
If you only want to check if a "Mercedes" is in the array use the php function 'in_array' (SEE DOC)
<?php
$cars=array("Volvo","BMW","Toyota");
if(in_array("Mercedes",$cars)) {
echo "OK ";
}
else
{
echo "NO ";
}
?>
This question already has answers here:
PHP if not equal(!=) and or (||) issue. Why doesnt this work?
(6 answers)
Closed 4 years ago.
Hope u people will be fine.
I’m working on a following code in which i want to use multiple php if conditions with multiple not operators (example is below), but when i execute following php code, it always returns true (mean content in always parenthesis always executed) even no condition is true.
I want to ask what is the problem in following code. Is there any specific syntax or rule for using multiple != operator in php conditions. And i am amazed to see that if i use following code by replacing != operator with == operator it is working fine.
if( $ext!="exe" || $ext!="html" || $ext!="htm" || $ext!="js" || $ext!="iso" || $ext!="zip" || $ext!="rar" )
{ // ececk extension
echo $ext."extension";
}
else{
echo "not match";
}
Waiting for your kind replies. and sorry for my bad english.
Better code:
$allowed = array('jpeg','png');
if(in_array($ext,$allowed)){
echo "Correct";
}
else {
echo "Wrong";
}
User XOR operator instead of OR as or checked all condition need to be identical while XOR return true if anyone from all is identical:
if(!($ext!=="exe") xor ($ext=="html")){ //Add more conditions
//each condition in new brackets & ! sign in start before all conditions
{ // ececk extension
echo $ext."extension";
}
else{
echo "not match";
}
Hope it will help
A new problem has arisen for me as I tried to run my script on a different PHP Server.
ON my old server the following code appears to work fine - even when no s parameter is declared.
<?php
if ($_GET['s'] == 'jwshxnsyllabus')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml', '../bibliographies/jwshxnbibliography_')\">";
if ($_GET['s'] == 'aquinas')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">";
if ($_GET['s'] == 'POP2')
echo "<body onload=\"loadSyllabi('POP2')\">";
elseif ($_GET['s'] == null)
echo "<body>"
?>
But now, on a my local server on my local machine (XAMPP - Apache) I get the following error when no value for s is defined.
Notice: Undefined index: s in C:\xampp\htdocs\teaching\index.php on line 43
Notice: Undefined index: s in C:\xampp\htdocs\teaching\index.php on line 45
Notice: Undefined index: s in C:\xampp\htdocs\teaching\index.php on line 47
Notice: Undefined index: s in C:\xampp\htdocs\teaching\index.php on line 49
What I want to happen for the script to call certain javascript functions if a value is declared for s, but if nothing is declared i would like the page to load normally.
Can you help me?
Error reporting will have not included notices on the previous server which is why you haven't seen the errors.
You should be checking whether the index s actually exists in the $_GET array before attempting to use it.
Something like this would be suffice:
if (isset($_GET['s'])) {
if ($_GET['s'] == 'jwshxnsyllabus')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml', '../bibliographies/jwshxnbibliography_')\">";
else if ($_GET['s'] == 'aquinas')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">";
else if ($_GET['s'] == 'POP2')
echo "<body onload=\"loadSyllabi('POP2')\">";
} else {
echo "<body>";
}
It may be beneficial (if you plan on adding more cases) to use a switch statement to make your code more readable.
switch ((isset($_GET['s']) ? $_GET['s'] : '')) {
case 'jwshxnsyllabus':
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml', '../bibliographies/jwshxnbibliography_')\">";
break;
case 'aquinas':
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">";
break;
case 'POP2':
echo "<body onload=\"loadSyllabi('POP2')\">";
break;
default:
echo "<body>";
break;
}
EDIT: BTW, the first set of code I wrote mimics what yours is meant to do in it's entirety. Is the expected outcome of an unexpected value in ?s= meant to output no <body> tag or was this an oversight? Note that the switch will fix this by always defaulting to <body>.
Get into the habit of checking if a variable is available with isset, e.g.
if (isset($_GET['s']))
{
//do stuff that requires 's'
}
else
{
//do stuff that doesn't need 's'
}
You could disable notice reporting, but dealing them is good hygiene, and can allow you to spot problems you might otherwise miss.
I always use a utility function/class for reading from the $_GET and $_POST arrays to avoid having to always check the index exists... Something like this will do the trick.
class Input {
function get($name) {
return isset($_GET[$name]) ? $_GET[$name] : null;
}
function post($name) {
return isset($_POST[$name]) ? $_POST[$name] : null;
}
function get_post($name) {
return $this->get($name) ? $this->get($name) : $this->post($name);
}
}
$input = new Input;
$page = $input->get_post('page');
I was having the same problem in localhost with xampp. Now I'm using this combination of parameters:
// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);
php.net: http://php.net/manual/pt_BR/function.error-reporting.php
First check the $_GET['s'] is set or not. Change your conditions like this
<?php
if (isset($_GET['s']) && $_GET['s'] == 'jwshxnsyllabus')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml', '../bibliographies/jwshxnbibliography_')\">";
elseif (isset($_GET['s']) && $_GET['s'] == 'aquinas')
echo "<body onload=\"loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')\">";
elseif (isset($_GET['s']) && $_GET['s'] == 'POP2')
echo "<body onload=\"loadSyllabi('POP2')\">";
elseif (isset($_GET['s']) && $_GET['s'] == null)
echo "<body>"
?>
And also handle properly your ifelse conditions
I recommend you check your arrays before you blindly access them :
if(isset($_GET['s'])){
if ($_GET['s'] == 'jwshxnsyllabus')
/* your code here*/
}
Another (quick) fix is to disable the error reporting by writing this on the top of the script :
error_reporting(0);
In your case, it is very probable that your other server had the error reporting configuration in php.ini set to 0 as default.
By calling the error_reporting with 0 as parameter, you are turning off all notices/warnings and errors. For more details check the php manual.
Remeber that this is a quick fix and it's highly recommended to avoid errors rather than ignore them.
You should check wheter the index exists before use it (compare it)
if (isset($_GET['s']) AND $_GET['s'] == 'foobar') {
echo "foo";
}
Use E_ALL | E_STRICT while developing!
Actually none of the proposed answers, although a good practice, would remove the warning.
For the sake of correctness, I'd do the following:
function getParameter($param, $defaultValue) {
if (array_key_exists($param, $_GET)) {
$value=$_GET[$param];
return isSet($value)?$value:$defaultValue;
}
return $defaultValue;
}
This way, I check the _GET array for the key to exist without triggering the Warning. It's not a good idea to disable the warnings because a lot of times they are at least interesting to take a look.
To use the function you just do:
$myvar = getParameter("getparamer", "defaultValue")
so if the parameter exists, you get the value, and if it doesnt, you get the defaultValue.
Avoid if, else and elseifs!
$loadMethod = "";
if(isset($_GET['s'])){
switch($_GET['s']){
case 'jwshxnsyllabus':
$loadMethod = "loadSyllabi('syllabus', '../syllabi/jwshxnporsyllabus.xml', '../bibliographies/jwshxnbibliography_')";
break;
case 'aquinas':
$loadMethod = "loadSyllabi('syllabus', '../syllabi/AquinasSyllabus.xml')";
break;
case 'POP2':
$loadMethod = "loadSyllabi('POP2')";
}
}
echo '<body onload="'.$loadMethod.'">';
clean, readable code is maintainable code
Simple function, works with GET or POST. Plus you can assign a default value.
function GetPost($var,$default='') {
return isset($_GET[$var]) ? $_GET[$var] : (isset($_POST[$var]) ? $_POST[$var] : $default);
}
Another option would be to suppress the PHP undefined index notice with the # symbol in front of the GET variable like so:
$s = #$_GET['s'];
This will disable the notice. It is better to check if the variable has been set and act accordingly.
But this also works.
The real answer to this is to put a # At symbol before the variable which will suppress the error
#$_GET["field"]
#$_POST["field"]
It will work some slower, but will keep the code clean.
When something saves time for the programmer, and costs time for the website users (or requires more hardware), it depends on how much people will use it.