Using if in a array php [closed] - php

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 ";
}
?>

Related

I am unable to understand below php Function code - [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
How it will print hello - If hello is true, then the function must print hello, but if the function doesn’t receive hello or hello is false the function must print bye.
<?php
function showMessage($hello=false){
echo ($hello)?'hello':'bye';
}
?>
So if you don't want any condition you can add default value bye to para,eter. And simply echo it
<?php
function showMessage($hello="bye"){
echo $hello;
}
?>
Basically ($hello)?'hello':'bye'; is the shorthand for:
if ($hello == true) {
echo 'hello';
} else {
echo 'bye';
}
Reference: http://php.net/manual/en/control-structures.if.php
You are using ternary operator inside function, which will check the type of variable true or false. By default $hello variable type will be false.
So below code will be check if variable type is true then prine 'hello' else ternary operator will be print 'bye'.
It is same as like below
if($hello==true){
echo 'hello';
}else{
echo 'bye';
}
The reason why showMessage('abc') now prints 'hello' is because the ($hello) will evaluate to true as a non-empty string.
I guess what you are looking for is the type comparison operator ===. It will check whether the argument passed is actually a boolean value.
function showMessage($hello=false) {
echo ($hello === true)?'hello':'bye';
}

Loop only if condition is met? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Is it possible to do something like this:
if ($boolean == true) {
foreach ($variables as $variable) {
}
// some code that can be run either with a loop or without
if ($boolean == true) {
} // end the foreach loop
}
Or is there another way to do this without rewriting the same code twice just to satisfy all possibilities?
The conventional way is to always use a loop. If there is only one item, then you can still loop just once.
Contrived example
$values = …;
if (!is_array($values)) {
$values = array($values);
}
foreach ($values as $value) {
// Do your work
}
I'm not sure if I understand exactly what you're asking, but if you want to run a loop at least once, and continue looping for a condition then "Do While" is your answer. A do while works just like a while, but checks AFTER the first loop is run - meaning it always runs at least once.
PHP Docs for Do While
Do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning.
Example:
$arrayofstuff = array('one ','two ','three '); // Optional array of stuff
$i=0; // Counts the loops
echo 'starting...';
do {
// Do stuff at least once here
// Array stuff if needed
if(isset($arrayofstuff[$i])) {
echo $arrayofstuff[$i]; // Uses loop # to get from array
} else {
break; // ends loop because array is empty
}
$i++;
} while (true);
For what it's worth, forcing a variable into a single value array would probably be easier to read. As you can see there's a lot going on here for such a simple task.
(Dionne Warwick voice) That's what functions are for:
function doSomething() {
//whatever
};
if ($boolean)
for($variables as $variable) doSomething();
else
doSomething();
That kind of syntax you thought about isn't valid in PHP. It's a very clever idea though. But code maintenance of one of there would bring hell on earth. Better forget it.
why not just plain:
if($boolean){
foreach($a as $b){
// do stuff
}
}else{
// do other stuff
}
What you want would be done like so...
foreach ($variables as $variable) {
// some code that can be run either with a loop or without
if ($boolean !== true) {
break;
}
}
But this is not as readable as just using an if/else statement

How can i have and or together? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Im wondering if i can do and/or together. I'm trying to make a code that checks if both variables are wrong or if only one of them is wrong and the other one is right then I want to show a message like: "one of the "variables" are wrong.
Can anyone help me out here?
In addition to Tim Whites answer, if you don't want it nested, you could also use:
if($a == false AND $b == false) { echo "Both variables are false"; }
elseif($a == false OR $b == false) { echo "One variable is false"; }
if ($a==false OR $b==false) {
if($a==false AND $b==false) { echo "Both variables are false"; }
else { echo "On of the variables is false"; }
}
Something like that will do.
You could just use multiple IF statements, to check if 1 variable is wrong or both are wrong. Like:
if ($variable1==false && $variable2==false){
}
else{
if ($variable1==false || $variable2==false){
}
}

Error in syntax for if statement in codeigniter? [duplicate]

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".

Is there a better way of determining empty associative arrays in php 5.3?

The empty() function in php 5.3 does not work well for associative arrays. I have an associative array that could have some 30+ elements.
$arr = array(
'one'=>kwara,
'two'=>osun,
...
'thirty'=>lagos
)
If the associative array is empty like so:
$arr = array(
'one'=>'',
'two'=>'',
...
'thirty'=>''
)
and I need to check if the array is empty, the following will not work in php 5.3.
if(empty($arr))
{
echo "array is empty<br />>";
}
else
{
echo "array is NOT empty<br />";
}
and will return 'array is NOT empty'. I am aware that the behaviour is different in php 5.4 but my current platform is php 5.3.
To overcome this problem, I have used the following:
if(strlen(implode('',array_values($arr))) > 0)
{
echo "array is NOT empty<br />>";
}
else
{
echo "array is empty<br />";
}
The question is: is there a better of achieving this in php 5.3?
Short answer: No
Longer answer: The array you are looking at is not empty at all, it contains a bunch of keys with zero length strings. Your solution is probably one of the shortest possible and readable. You may want to wrap it in a function of your own though.
Have you tried:
if (sizeof(array_filter($array)) === 0) // do your stuff
Also you original could be improved like:
if (implode($array) !== '') // do your stuff
Empty will work only with really empty values, your array has keys assigned so its not empty. Your solution is probably best way to do what you want - its hard to say, you would need to make some benchmarks, it can be done in many other ways:
if (array_filter($arr) === array()) {}
// or
if (!implode('', $arr)) {}

Categories