Asked  7 Months ago    Answers:  8   Viewed   123 times

It often happens to me to handle data that can be either an array or a null variable and to feed some foreach with these data.

$values = get_values();

foreach ($values as $value){
  ...
}

When you feed a foreach with data that are not an array, you get a warning:

Warning: Invalid argument supplied for foreach() in [...]

Assuming it's not possible to refactor the get_values() function to always return an array (backward compatibility, not available source code, whatever other reason), I'm wondering which is the cleanest and most efficient way to avoid these warnings:

  • Casting $values to array
  • Initializing $values to array
  • Wrapping the foreach with an if
  • Other (please suggest)

 Answers

63

Personally I find this to be the most clean - not sure if it's the most efficient, mind!

if (is_array($values) || is_object($values))
{
    foreach ($values as $value)
    {
        ...
    }
}

The reason for my preference is it doesn't allocate an empty array when you've got nothing to begin with anyway.

Wednesday, March 31, 2021
 
Santi
answered 7 Months ago
61

Add if condition before foreach:

<?php
$loan_club = get_the_terms(get_the_ID(), 'loan-club');

if(is_array($loan_club)) {
    foreach ($loan_club as $cat) {
      ?>
        <img src="<?php echo z_taxonomy_image_url($cat->term_id); ?>" title="ON LOAN AT: <?php echo $cat->name; ?>" />
      <?php
    } 
}
?>

Look at get_the_terms() function in the documentation: https://developer.wordpress.org/reference/functions/get_the_terms/

The function may also return WP_Error or false. If WP_Error or false is returned this will cause the error and the foreach loop breaks.

Wednesday, March 31, 2021
 
maniclorn
answered 7 Months ago
90

I'm not sure what's going on, and I am very new to PDO, so I'm not sure how to troubleshoot this.

What's going on is, that you've got an empty database result. If you foreach over an empty result, there are no (zero) iterations. Hence you see no output and hence you see no error. It's a perfectly fine programming of doing nothing.

How to troubleshoot? I think it's best to understand the difference between an empty database result and a failed database query. E.g. as long as you have a query that selects rows, there is a rowCount() method with the result object.


Additional remarks:

  • You are using PHP short-tags <?, please see "Are PHP short tags acceptable to use?" and understand the potential problems this carries. We kindly asks users when posting PHP source-code on this website here to not use them to address the question to the general audience (as this is the intention of this website).
  • The output code you have should not contain the database interaction. You can achieve this by only passing the $rows variable in there and move the if-clause around it.
  • Assigning NULL to the $database variable only to unset($database); it is not necessary in PHP.
  • You do not need to unset($database); at all. PHP will clean this up for you when you end the script. If you want to close the database connection in PDP and you're using mysql, please see "Do SQL connections opened with PDO in PHP have to be closed" and if you really need to close the connection, you can learn how this can be done in this answer to it.
Wednesday, March 31, 2021
 
xenon
answered 7 Months ago
83

Just modify this line

foreach ($query->result() as $row) {

To

foreach ((array)$query->result() as $row) {

Friday, May 28, 2021
 
Kevin_Kinsey
answered 5 Months ago
86

Change this:

$path[] = $dir;
foreach($path as $dirname){
    $add = glob($dirname . '/*.css');
    foreach($add as $file){

to this:

$path[] = $dir;
var_dump($path);
foreach($path as $dirname){
    $add = glob($dirname . '/*.css');
    var_dump($add);
    foreach($add as $file){

We don't know which line 131 is, so I don't know which foreach fails.

(I'm guessing the 2nd, because the first is practically forced to array by $path[] = ..)

Saturday, May 29, 2021
 
jcubic
answered 5 Months ago
47

After your most recent update of the code: The answer to the error message in the question title is:

The code is missing the line $users = file("test.txt");

Saturday, May 29, 2021
 
Floris
answered 5 Months ago
50

Double check to ensure that $jsonObj->d->results is indeed an array or that its not empty.

if( ( is_array( $jsonObj->d->results ) && ( ! empty( $jsonObj->d->results ) ) {
    foreach($jsonObj->d->results as $value)
    {
        switch ($value->__metadata->type)
        {
            case 'WebResult':
            $resultStr .= "<a href="{$value->Url}">{$value->Title}</a><p>{$value->Description}</p>";
            break;
            case 'ImageResult': $resultStr .= "<h4>{$value->Title} ({$value->Width}x{$value->Height}) " . "{$value->FileSize} bytes)</h4>" . "<a href="{$value->MediaUrl}">" . "<img src="{$value->Thumbnail->MediaUrl}"></a><br />";
            break;
        }
    }
} else {
    if( ! is_array( $jsonObj->d->results ) {
        echo "jsonObj->d->results is not an array!";
    } elseif( empty( $jsonObj->d->results ) {
        echo "jsonObj->d->results is empty!";
    }
}
Saturday, May 29, 2021
 
jakubos
answered 5 Months ago
69

you need to do a check before starting to iterate for the data, like: model code:

public function getAll() {
    $results = array();
    $this->db->select('bcode, bname, btel, badd');
    $this->db->from('branches');

    $query = $this->db->get();

    if($query->num_rows() > 0) {
        $results = $query->result();
    }
    return $results;
}

view code:

if( !empty($results) ) {
    foreach($results as $row) {
        echo '<tr>';
        echo '<td>'.$row->bcode.'</td>';
        echo '<td>'.$row->bname.'</td>';
        echo '<td>'.$row->btel.'</td>';
        echo '<td>'.$row->badd.'</td>';
        echo '</tr>';
    }
}
Sunday, August 15, 2021
 
Boris
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :