Checking for Array

In my latest script, if an Article has no Comments, then the loop below fails…


	foreach($commentsArray as $commentKey => $subArr){

	}

What is the best way to code things to handle this?

The only thing I can think of is to stick my loop inside of an IF-THEN-ELSE, but that seems sloppy and verbose…

Is there maybe a better approach to take?

Sincerely,

Debbie

Try this:



 if ( isset($commentsArray) && is_array($commentsArray ) && count($commentsArray) > 0 ):

   foreach($commentsArray as $commentKey => $subArr):
     //
    endif;  

else:
   echo 'Yes we have no $commentsArray';

endif;



What’s the isset() part for??

Debbie

isset() is a “Belt & Braces” check to ensure the variable has been set.

Assuming you are using PDO, you can just use fetchColumn()


$query = "SELECT comments FROM comments_table";
$results = $pdo->prepare( $query );
$results->execute();

if( $results->fetchColumn() >= 1 ) {
    foreach($results as $commentKey => $subArr) {
        // Do stuff
    }
}
else {
    echo 'Nothing to see';
}

If you’re using mysqli, you can use mysqli_num_rows()

Well, I start my script off with…


$commentsArray = array();

And then I display my Comments like this…


	// Display Comments.
	if ($articleCommentCount == 0){
		// No Comments Exist.
		echo "<p id='noComments'>No Comments exist.<p/>";
									
	}else{
		// Comments Exist.
		foreach($commentsArray as $commentKey => $subArr){

		}
}

The only place I think I need to fix is when the Form is submitted…

Technically - as shown above - if there are no Comments, there wouldn’t be a Form to submit.

But let’s say that is somehow possible, then how could I improve this…


	// HANDLE FORM.
	if ($_SERVER['REQUEST_METHOD']=='POST'){

		foreach($commentsArray as $commentKey => $subArr){
			if ($subArr['commentID'] == $reviewedCommentID){
				$reviewedCommenterID = $subArr['commenterID'];
				$reviewedCreatedOn = $subArr['createdOn'];
			}
		}
	}

If I just initialize $reviewedCommenterID and reviewedCreatedOn I think I am okay, but maybe I should do more??

BTW, I am using Prepared Statements…

Sincerely,

Debbie

As you can see in my last post, I think my question relates to my array and not my earlier query.

Sincerely,

Debbie

It is difficult to recommend further improvements when only a small snippet of the complete script is shown.

It appears that there could be many items in the $commentsArray and only a single or the last match that satisfies the if(…) statement allocates $reviewedCommenterID and $reviewedCreatedOn.

I would have thought that it would have been far more efficient to allocate the two variables from a SQL query which I believe is far quicker than PHP processing scripts.

Also expect errors because only the double equal comparison is used. Fewer problems arise if testing for an exact match where the variable type is also compared using the treble equal sign.

Just before you’re loading data into the $commentsArray, add this line:


$commentsArray=array();

That will set up $commentsArray as an empty array so that when the foreach loop is given $commentsArray to work with, if there are no comments it’ll see an empty array.

Try the code John gave up top; as you already figured out, the code I gave you was for a different point in the script.

John, I think your answer in Post #2, combined with me reviewing my current approach is what I need to makes things fail-proof.

And, yes, when I do this again in my next version, I will definitely see if I can come up with a better approach!

Thanks!

Debbie

Yes, I did that.

And adding John’s tip above should help finish things off…


if (count($commentsArray) > 0){

   foreach($commentsArray as $commentKey => $subArr):
     // do something
   }

}else{
   // Throw some error

}

Thanks all! :slight_smile:

Debbie