The foreach statement in PHP is functioning correctly, however, the message in the else statement is

I have been working on fetching data from my model as an array and using a php foreach loop to display it in a specific view. I am now trying to implement an additional layer of logic to only display certain bookmark_ids.

Even though the data is being displayed correctly, I am facing an issue where the "else" message (associated with the initial if statement) does not appear when no data is returned. I need to find a way to ensure that this message is shown.

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

?>

Answer №1

To test the existence of $bookmark, assume it is always present, with either empty or array values.

Give this a try:

<?php 

if (is_array($bookmark) && count($bookmark)>=1): 
  foreach($bookmark as $b):               

    if ($b->bookmark_id != 0) {              

      <li><?php echo $bk->bookmark_name; ?></li>

    }

  endforeach;
else:
  print "Your bookmark list is currently empty.";
endif;

?>

Refer to: PHP is_array() | count()

REVISITED

In response to the recent comment "Yes, the array has results; I am using the second if statement for display restriction. It appears that my else statement should be linked to the second if condition, rather than the first one. My concern is not about having results but filtering them and checking what remains.":

<?php 

// reset the counter
$count = 0;

// for an array that 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++; // increase if no data
    }

    // check if the counter was incremented 
    if ($count>=1) {
      print "Your bookmark list is empty.";
    }
  endforeach;
else:
  print "No bookmarks found.";
endif;

?>

Answer №2

It seems that $bookmark is returning true for some reason. Given that empty strings and arrays evaluate to false in PHP, it's likely that $bookmark is actually an object. Based on its ability to be iterated over with foreach, it may be an instance of a class like ArrayObject. To determine the exact type of $bookmark, you could use:

var_dump($bookmark);

Since an empty object evaluates to true in a PHP conditional, it's important to be more specific about what condition you're checking for.

if(count($bookmark) > 0):

This should appropriately trigger the else condition. Additionally, remember to properly indent your code for better readability. :)

Answer №3

if (is_array($saved) && !empty($saved)) { 
  foreach ($saved as $link) {               
   ...
  }
} else {
  echo "There are no saved bookmarks.";
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to incorporate a text box in javascript that displays the retrieved reference count from the database?

I'm currently working on creating a functionality that retrieves rows with the same ID from a database and displays them in a text box. Below is the PHP code I've written for retrieving all the rows: PHP: <?php include_once('pConfig ...

Start creating a Laravel project

Compiling Entire Laravel Project: Is there a way to easily compile and build the entire Laravel project at once? This process would help identify any exceptions that may occur throughout the project. In languages like .NET and Java, developers have IDEs t ...

Is it possible to transfer funds to another PayPal account using the PayPal API? If so, what steps are involved in

As a small business owner, I frequently transfer money using PayPal to other PayPal accounts. I'm curious if it's possible to automate this process using the PayPal API. Can anyone advise on the best way to achieve this efficiently? ...

Compose an email containing customized content for the group of recipients pulled from the database

Hello, I am facing an issue with sending personalized emails to a list of users from my database. Each user needs to receive a unique link in their email. Here is the content of the email: Dear User, There is an important message for you. Click on the l ...

Retrieve attributes of an html element modified by AJAX request

I am currently developing a small project that involves performing CRUD operations on a MySQL table using PHP and jQuery. The table is integrated into the layout in the following manner: <?php require '../connect.php'; $sql = "SELECT id ...

Retrieve information from the database and showcase it in a drop-down list using the CodeIgniter framework

I encountered an error while using CodeIgniter. A PHP Error occurred Severity: Notice Message: Undefined variable: assigned_to Filename: admin/insert.php Line Number: 20 A PHP Error occurred Severity: Warning Message: Invalid argument supp ...

Ways to divide a foreach loop or for loop into sets of 10 records

Let's say I have 56 entries in my database. To display them, I am using a FOR LOOP. My goal is to add a div element after every set of 10 records. <?php $totalRecords = 56; for($i=0; $i<$totalRecords; $i++){ e ...

Issue with the PHP/AJAX (jQuery) chat function

I have developed a Chat script using PHP and jQuery, but I am concerned about the potential strain it may put on the server. Can anyone provide assistance with this? If you have an answer, please share it with me. Thank you in advance. ...

Validation of VAT numbers using JavaScript instead of PHP

I came across an interesting function at this link that is used for checking VAT numbers in the EU. However, I am struggling to integrate it with my registration form. I would like to convert it into a JavaScript function so that I can validate the number ...

Having trouble opening large XML files in Excel?

My PHP script successfully generates an XML file from a database, but I'm encountering an issue with larger files. The table in the database has 53 columns. Excel can easily open a file with 7000 rows (20Mb), but once it reaches around 14000 rows (40 ...

I am currently working with a for loop within an object in JavaScript, but there seems to be a problem with one

Here is a function called validator: import validator from "validator"; import isEmpty from "is-empty"; export default function validate(data) { const errors = {}; for (const property in data) { console.log(property); //< ...

Click on the following link to access the YouTube video

I am looking to develop a PHP application that can be used to download videos from YouTube. For example: page with video: http://www.youtube.com/watch?v=5dT312CDPJI link to video: <a href="http://o-o.preferred.tpnet-waw2.v24.lscache1.c.youtube.com/vid ...

Decode JSON with an integer as the key

Alright, so here's the situation. I've got this massive JSON feed and everything is running smoothly. However, there's just one small hiccup Currently, my approach involves: $json=file_get_contents($source); $data = json_decode($json,true) ...

Issues with decoding JSON data in PHP

Struggling to assign a JSON Object to a PHP Variable? When attempting to use var_dump, it's showing NULL. Here is the PHP code: <?php $json = utf8_encode(file_get_contents('http://socialclub.rockstargames.com/ajax/stat/1/profile_body/sta1/ ...

CSS grid is organizing itself neatly on larger screens

I'm currently facing an issue with displaying a CSS grid on my page. When viewed on desktop, the grid appears stacked up instead of in separate columns. I've tried various methods like dividing it into 4 columns and using spans for width but noth ...

SQL retrieve data sorted by result column and return it as an array

Wondering if it's possible to retrieve groups as an associative array using SQL. I'm interested in understanding the capabilities of SQL and its potential for solving this particular issue. The challenge at hand involves a database containing a ...

Transferring session data through AJAX in PHP

I'm currently developing an app using PhoneGap. However, PhoneGap only supports HTML, CSS, and JS, not PHP. This led me to the workaround of placing the PHP file on a remote server and using AJAX to call it via the server's URL. My issue now is ...

Is it possible to transmit information to a PHP script using jQuery's post function without triggering a page reload?

I am working on a form submission that needs to happen without refreshing the page. The objective is to receive the form data and manipulate it within the same page. The form's purpose is to add a new row in the clients table, and I need to retrieve ...

Can the .htaccess files be merged together?

Currently, I am facing the challenge of overhauling an existing website that is riddled with spaghetti code and relies on rewrite rules to create friendly URLs. Unfortunately, there are critical issues within the architecture and database structure that c ...

Dealing with incoming data in a yii2 RESTful service

When sending an array using $http post, I follow this approach: var results = services.transaction('orderdetails/insert', {customer_id: $scope.order.customer_id, data: $scope.orderDetail}); The variable $scope.orderdetail ...