1

I am getting an error on this line:

$ret = array_merge($ret, preg_ls($path . "/" . $e, $rec, $pat));

Error is:

array_merge() Argument #2 is not an array

I don't know know to solve this.

function preg_ls($path = ".", $rec = false, $pat = "/.*/") {
    // it's going to be used repeatedly, ensure we compile it for speed.
    $pat = preg_replace("|(/.*/[^S]*)|s", "\\1S", $pat);
    //echo($pat);
    //Remove trailing slashes from path
    while (substr($path, -1, 1) == "/")
        $path = substr($path, 0, -1);
    //also, make sure that $path is a directory and repair any screwups
    if (!is_dir($path)) $path = dirname($path);
    //assert either truth or falsehoold of $rec, allow no scalars to mean truth
    if ($rec !== true)
        $rec = false;
    //get a directory handle
    $d = dir($path);
    //initialise the output array
    $ret = Array();
    //loop, reading until there's no more to read
    while (false !== ($e = $d->read())) {
        //Ignore parent- and self-links
        if (($e == ".") || ($e == "..")) continue;
        //If we're working recursively and it's a directory, grab and merge
        if ($rec && is_dir($path . "/" . $e)) {
            $ret = array_merge($ret, preg_ls($path . "/" . $e, $rec, $pat));
            continue;
        }
        //If it don't match, exclude it
        if (!preg_match($pat, $e))
            continue;
        //In all other cases, add it to the output array
        //echo ($path . "/" . $e . "<br/>");
        $ret[] = $path . "/" . $e;
    }
    //finally, return the array
    echo json_encode($ret);
}
4
  • if preg_ls is returning a json string then you can't pass it to array_merge because it's expecting an array. Commented Apr 1, 2013 at 21:20
  • ...json_encode() gives a string, not an array. Commented Apr 1, 2013 at 21:20
  • return $ret; instead of echo json_encode($ret) Commented Apr 1, 2013 at 21:21
  • preg_ls returns nothing and array_merge expects an array Commented Apr 1, 2013 at 21:21

1 Answer 1

6

An Array in PHP is not JSON. It's an array. Simply return $ret;

You should return the array if you are expecting an array, not a string (as json_encode gives).

Also, you are using echo, not return. echo prints to either stdout or the HTML body, depending on the PHP environment (though they are one and the same, just with redirects and a different environment to handle it).

return will cause a function to pass its return value to the caller, as expected (usually into a variable or another function); without a return value, the function will always return NULL.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.