if else condition not working with array values in php - php

i have come to this strange issue.
i am getting values from array and trying to compare it but its not working.
Code-1
<?php
echo $data->item[0]['promocode'].'<br>';
echo $data->item[1]['promocode'];
?>
Output-1
inhouse
inhouse
Now lets try with if else condition if both values are same or not
Code-2
<?php
if(($data->item[0]['promocode']) == ($data->item[1]['promocode'])){
echo "both values are same";
} else {
echo "both values are NOT same";
}?>
Output-2
both values are NOT same
Very strange
i dont get it what i am doing wrong.
lets try above exaple with specifying variables
Code-3
<?php
$data0=$data->item[0]['promocode'];
$data1=$data->item[1]['promocode'];
if($data0 == $data1){
echo "both values are same";
} else {
echo "both values are NOT same";
}?>
Output-3
both values are NOT same
I am pulling my hairs now.
Now hard coding values in variables
Code-4
<?
$data0='inhouse';
$data1='inhouse';
if($data0 == $data1){
echo "both values are same";
} else {
echo "both values are NOT same";
}?>
Output-4
both values are same
So my question is why is this happening ?
i have array of elements and i wanna check previous value with the current value if try then do something.
thanks for your time.

Assuming both entries are strings (as shown in your first code example) my guess would be that your entries have unequal leading and / or trailing whitespace. Try normalising them first, eg
if (trim($data->item[0]['promocode']) == trim($data->item[1]['promocode']))
To see what's going on, try modifying your first example to
<?php
printf('<pre>"%s"%s"%s"</pre>',
$data->item[0]['promocode'],
PHP_EOL,
$data->item[1]['promocode']);
?>

Try like this
<?php
if(($data->item[0]['promocode']) === ($data->item[1]['promocode'])){
echo "both values are same";
} else {
echo "both values are NOT same";
}
?>
or you can use
strcmp($data->item[0]['promocode'],$data->item[1]['promocode']);

I use strlen($var) also for debugging...
<?php
if( strlen($data->item[0]['promocode']) == strlen($data->item[1]['promocode']) ){
if(($data->item[0]['promocode']) == ($data->item[1]['promocode'])){
echo "both values are same";
}
else {
echo "both values are NOT same";
}
}
else{
echo 'ther are different because
strlen($data->item[0]["promocode"]='.strlen($data->item[0]['promocode']).' and
strlen($data->item[1][|promocode"]) = '. strlen($data->item[1]['promocode']);
}
?>

Try using the non-type-casted conditional statement === to see if they are the same type.
Or for debugging perposes display the variable type to make sure you don't accidentally have some NULL objects or other weird data types.
if($data0 !== $data1) echo gettype($data0).' !== '.gettype($data1);
That should help you find out what you're actually comparing. Another option is to use var_dump($data); to actually display the variables all together. See if theres some discrepancies in the data types. It should help you find out if your object is actually populating correctly.

Related

Checking if two variables are not empty in PHP

I want to echo variables if either of them aren't empty.
I have written the following PHP but they aren't being shown when the variables aren't empty:
if(!empty($this->element->videos||$this->element->productdownloads)) {
echo $this->element->videos;
echo $this->element->productdownloads;
}
When checking with the OR operator (||) the code will execute if one or none of them is empty. But you echo both variables even if one of them is empty.
What I think you want to do is use the AND operator(&&). This way, the code will only execute if none of the variables are empty.
<?php if(!empty($this->element->videos) && !empty($this->element->productdownloads)) {
echo $this->element->videos;
echo $this->element->productdownloads; }
?>
if you still want to show videos, even if productdownloads is empty (and vice versa), you could do a seperate if for each of them, like this:
if(!empty($this->element->videos){
echo $this->element->videos;
}
if(!empty($this->element->productdownloads){
echo $this->element->productdownloads;
}
edit: minor grammatical fixes
<?php
if(!empty($this->element->videos) || !empty($this->element->productdownloads)) {
echo $this->element->videos;
echo $this->element->productdownloads;
}
?>
if(!$this->element->videos || !$this->element->productdownloads)
{
echo $this->element->videos;
echo $this->element->productdownloads;
}
You dont need to use empty by default php checks for empty when you use ! sign with if condition
Try
if(!($this->element->videos && $this->element->productdownloads)){
echo $this->element->videos;
echo $this->element->productdownloads;
}
Well, I have had quite number of issues like that.
Try to remove empty space from the two variables before comparing them. Sometimes empty spaces comes before the variable and that hinders comparison.

equals to comparison not working even though the values are same

Here is the php code where am comparing the two values. The courses values are what I passed from controller that is coming from the database and prev_course has the value previously selected. Though the comparison becomes same for one time it showing the else part of code every time. As you can see the 3rd output is same GRE and GRE but still showing not same
The output of the code comes like this
not same
prev course= GRE and from db=IELTS
not same
prev course= GRE and from db=TOFELS
not same
prev course= GRE and from db=GRE
here is the php code for comparison I have tried both == and ===
<?php foreach($instructor_course as $courses):?>
<?php if($courses['name']===$prev_course):?>
<?php echo 'same<br/>';?><?php echo "prev course=$prev_course"." and from db=".$courses['name'] ."<br/>";?>
<?php else: ?>
<?php echo 'not same <br/>';?><?php echo "prev course=$prev_course"." and from db=".$courses['name'] ."<br/>";?>
<?php endif;?>
<?php endforeach;?>
Try this:
foreach($instructor_course as $courses) {
if($courses['name'] === trim($prev_course)) {
echo 'same<br/>';
echo "prev course=$prev_course and from db=$courses['name']<br/>";
} else {
echo 'not same <br/>';
echo "prev course=$prev_course and from db=$courses['name'] <br/>";
}
}

Using if else statement based off of $_POST value to echo message

Pretty sure this is a quick and easy question but I have a form that on action POST goes to a confirmation page. I need a message to display on the confirmation page if the user selects county1 but if user selects county2, county3, or county4. However, when I setup the statement it's not working. Probably a syntax error or two on my part. Any help would be greatly appreciated.
A messy idea of what I think should work:
<?php $county=$_POST['County'];
if ($county="Polk") {
echo "Important message about your county"; }
else {
echo " "; // Or nothing at all
}
?>
But
<?php echo $_POST['County'] ?>
displays the name of the county so I know the submission is carrying through. Thoughts on why my above code wouldn't be working? If you could flag syntax errors or code placement that'd be much appreciated! Thank you!
Inside the if condition you should use two equal operators instead of one . try this code
<?php
$county = isset($_POST['County'])?$_POST['County']:"";
if ($county == "Polk") {
echo "Important message about your county";
}
else {
echo " "; // Or nothing at all
}
?>
Use double equal in your if statement for comparison
See the answer and read the comment to understand why you have to change it
if ($county="Polk") {
Single equal is assignment operator, it assign value
Change this line to this
if ($county=="Polk") {
So your whole code should look like this
$county=$_POST['County'];
if ($county == "Polk") {
echo "Important message about your county";
}
else {
echo " "; // Or nothing at all
}
Use double equal sign, double equal is comparison operator,
Here you are checking if the $county is equal to Polk or not,
Means you are comparing value

php if foreach statement works, but else message not displaying

I'm getting an array of data from my model, and am using a php foreach statement to display it in a view. I'm adding another layer of logic to show only certain bookmark_ids.
The data is displaying fine; but for some reason the "else" message (tied to the first if clause) isn't showing if no data is returned. I need to figure out how to get that message to display.
<?php
if ($bookmark):
foreach($bookmark as $b): ?>
<?php if ($b->bookmark_id != 0) { ?>
<li><?php echo $bk->user_id; ?> <?php echo $bk->bookmark_name; ?></li>
<?php } ?>
<?php
endforeach;
else:
print "Your bookmark list is empty.";
endif;
?>
You a testing if $bookmark exists! I assume that it always exists, either empty or with array of values!
Try this:
<?php
if (is_array($bookmark) && count($bookmark)>=1):
foreach($bookmark as $b): ?>
<?php if ($b->bookmark_id != 0) { ?>
<li><?php echo $bk->bookmark_name; ?></li>
<?php } ?>
<?php
endforeach;
else:
print "Your bookmark list is empty.";
endif;
?>
Read: PHP is_array() | count()
EDITED
Related to the recently posted comment "Yes, the array is returning results; I am using the second if statement to limit what is shown. It sounds like my else statement should be tied to the second if clause, instead of the first. The issue for me isn't whether there are results; it's whether after the results are filtered anything remains.":
<?php
// reset variable
$count = 0;
// if it is an array and is not empty
if (is_array($bookmark) && count($bookmark)>=1):
foreach($bookmark as $b):
if ($b->bookmark_id != 0) {
echo '<li>' . $bk->bookmark_name . '</li>';
} else {
$count++; // no data, increase
}
// check if the counter was increased
if ($count>=1) {
print "Your bookmark list is empty.";
}
endforeach;
else:
print "bookmark not found.";
endif;
?>
For one reason or another, $bookmark is evaluating to true. Since empty strings and arrays already evaluate to false in PHP, we might reasonably suppose that $bookmark is in fact an object. Since we can iterate over it with foreach, it is probably an instance of ArrayObject, or a class that extends it. We could debug the exact type of $bookmark by writing:
var_dump($bookmark);
Since an empty object instance evaluates to true in a PHP conditional, we need to be more specific about what we're checking for.
if(count($bookmark) > 0):
This should trigger the else condition properly. As a side note, you should really indent your code properly. :)
if (is_array($bookmark) && !empty($bookmark)) {
foreach ($bookmark as $item) {
...
}
} else {
echo "Your bookmark list is empty.";
}

Check textarea with php

I have a textarea field and want to add a text or php code when the field is empty and if the field is not empty to add another php code. For example:
if the field is empty>do something.....else>do something...
I'm not good at php, so I'll be glad for any help.
Thanks.
p.s.Sorry for my english.
Assuming you're posting this from a form then you can do the following.
I'll write this out the long way so it's easier to understand:
if (!empty($_POST['TEXTAREA_NAME']){
// If the textarea is set then do something here
} else {
// If it is NOT set it then it will do the code here
}
<?php echo isset($_POST['texarea_name']) && !empty($_POST['texarea_name']) ? 'textarea not empty' : 'texarea is empty'; ?>
To test if outside variable is empty or not, you can just compare it with empty string
if ( $_POST['text'] === '') {
echo 'there was something';
} else {
echo 'nothing to say';
}

Categories