PHP Error: invalid argument supplied for foreach()

I’m trying to use this function at the bottom of a plugin’s main PHP file to determine if one of its action hooks is being used by the tag specified. However, I’m getting a “Warning” on the 2nd foreach in the code below. Why is this? Is there a better way to see if a WordPress action hook is being used?

<?php
function dump_hook($tag, $hook)
{
    ksort($hook);

    echo "<pre>>>>>>t$tag<br>";

    foreach ($hook as $priority => $functions) {

        echo $priority;

        foreach ($functions as $function) {
            if ($function['function'] != 'list_hook_details') {

                echo "t";

                if (is_string($function['function']))
                    echo $function['function'];

                elseif (is_string($function['function'][0]))
                    echo $function['function'][0] . ' -> ' . $function['function'][1];

                elseif (is_object($function['function'][0]))
                    echo "(object) " . get_class($function['function'][0]) . ' -> ' . $function['function'][1];

                else
                    print_r($function);

                echo ' (' . $function['accepted_args'] . ') <br>';
            }
        }
    }

    echo '</pre>';
}

$tag = array('anspress_loaded');
$hook = array('find_do_for_anspress');

dump_hook($tag, $hook);

Related posts

1 comment

  1. Some errors from your code:

    1.) $tag is array, but in your function it’s used as string:

    <?php 
    echo "<pre>>>>>>t$tag<br>";
    

    2.)$hook is array, so first foreach works ok:

    <?php
    // for first row
    // $priority is int 0
    // $functions is string find_do_for_anspress
    foreach($hook as $priority => $functions ) {}
    

    Next you try to do foreach with string $functions, but it’s not iterrable, so php says to you aforementioned error.

Comments are closed.