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.";
}
Related
I am trying to display a custom HTML page if the user that requests the page has the [is_vip] value equal to "5".
this is the line I'm trying to run:
<?php if ($membership["is_vip"] == 5) { ?>
do stuff
<?php } else {
do other stuff
However it's not displaying the custom results properly, the contents of $membership look like this when printed.
Array
(
[0] => napify\Model\Membership Object
(
[is_vip] => 5
)
)
This should be simple but i've been stuck in this for hours.
That's an integer indexed array with one element containing an object. Plus the code you posted won't parse and is a parse error. Once you fix the syntax:
<?php if ($membership[0]->is_vip == 5) { ?>
do stuff
<?php } else { ?>
do other stuff
<?php } ?>
Make sure to use error reporting when developing:
error_reporting(E_ALL);
ini_set('display_errors', '1');
I believe AbraCadaver is correct with their post
<?php if ($membership[0]->is_vip == 5) { ?>
but there is also an issue with your closing tag.
<?php } else {
should be
<?php } else { ?>
and your else statement needs to be closed with a
<?php } ?>
I'm working (for the firs time) with MVC model and I'm having some problems when displaying the errors warnings...
For example I got this
Controller:
include_once(UserModel.php);
$userdata = new User_Model();
$biography = $userdata->Get_UserBio();
Model:
include_once(conexion.php);
//I make my prepared query and...
if ($user_infoprofile->execute()):
$data= $user_infoprofile->get_result();
if ($data->num_rows):
while ($result=$data->fetch_array()):
$this->userbio[]=$result;
endwhile;
else:
//I want to display something like
$error= "you have to fill your bio",
echo $error;
endif;
else:
$error="invalid request";
echo $error;
endif;
return $this->userbio;
$user_infoprofile->close();
View:
include_once(UserController.php);
//if there are rows in the array I display
foreach...
//But heres my problem... if there are not rows in the array... I want to display something else
How can I do it? I'm kind of beginner on this, or is there any other more clean way to do it?
Use quotes in your require functions. Like this : include_once('UserModel.php');. If you want to display all errors, you can do it with this lines :
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(empty($var_array)){
echo "There is not results...";
}else{
foreach....
}
Do you mean how to check if the array is empty?
ok but, the problem is how to doit in a specific part of my view.php file... because If I use 'echo' this message will appear anywhere and not where I would want to...
In my code there is some IFs that all are the same and working, Except one!
Here is the code
<?php
if($tmp['data']=='0')
{
?>
some code...
<?php
}
?>
<?php
if($tmp['data']=='1')
{
?>
some code...
<?php
}
?>
<?php
if($tmp['data']=='a')
{
?>
some code...
<?php
}
?>
<?php
if($tmp['data']=='b')
{
?>
some code...
<?php
}
?>
<?php
if($tmp['data']=='c')
{
?>
some code...
<?php
}
?>
$tmp['data'] is a value that is fetched from SQL database (varchar type).
IFs are working for all values, but when I set the value in phpmyadmin to 'c', related IF doesn't execute.
Any idea?
You should really use else if if more than one condition is never going to be true.
to debug try to comment everything else and just keeping the if of c, make sure it is not case sensitive (eg. server may return C, but you may check for c)
Try this peice of code to see if it works (though its bit complicated)
if( strcasecmp((string)$tmp['data'],"c")==0)
{
.. code here
}
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/>";
}
}
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.