Two script completing the same task, which is the best way? I have the following two methods of completing the same task, however I'd like to know which is the preferred method and WHY? Or if there are any suggestions to complete the task in an even better, cleaner way.

The task

Find part 1 of $string in the example $string = '1/2/3/4'; so the first part would be '1'. 

Match that value to the corresponding 'id' from entries in the database, then return the 'filename' that corresponds to the 'id'. 

Then loop again until each part of the initial string has a corresponding value. 

The 'filename' values are each then output to a string delimited by a '/'.

EG. filename1/filename2/filename3/filename4

Option 1

$string = '1/2/3/4';

$change = str_replace('/',',',$string);

$result = $connection-&gt;query("SELECT id, filename FROM pages WHERE id IN($change) ORDER BY FIELD($change)");

while($row = $result-&gt;fetch_assoc()) {
    $match[] = $row;
}

foreach ($match as $array) {
    echo $array['filename'].'/';
}


UPDATE
This works fine if there are more than one parts to the string eg. '1/2/3/4' but I get the following error if just '1' is used.

Fatal error: Call to a member function fetch_assoc() on a non-object in C:\xampp\htdocs\admin\pages\test2.php on line 22

OR

Option 2

$string = '1/2/3/4';

$split = explode('/', $string);

$split = array_flip($split);

$result = $connection-&gt;query("SELECT id, filename FROM pages");

while ($row = $result-&gt;fetch_assoc()) {
    $new_array[$row['id']] = $row['filename'];
}

$matched = array_intersect_key($new_array, $split);

$join = implode('/', $matched); // join $matched as string.

echo $join;
$string = '1/2/3/4';

$change = str_replace('/',',',$string);

$result = $connection-&gt;query("SELECT id, filename FROM pages WHERE id IN($change) ORDER BY FIELD(id,$change)");

$new_string = "";
while($row = $result-&gt;fetch_assoc()) {
     $new_string .= $row['filename']."/";
}

$new_string = substr($new_string,0,-1);

echo $new_string;


Less looping - the match[] = $row was unnecessary IMO because you want a string back only...so you concatenate the file name with a / delimiter and then the last slash is removed with sub_str.

Updated the fixes including single query match.