0

I have an array about 1500 entries worth of file paths.

Some of them are in a sub directory which I want to remove, say "SUB/". For optimization's sake, which is the best option?

  • Foreach ($key=>$val) and string update $array[$key] = str_replace("_SUB_/","",$val);
  • Same as above, but do a if/then to only run the str_replace if the string starts with "SUB/"
  • Implode the array to a single string, run str_replace on that string, and then explode it back to an array
  • Something else I'm not thinking of

None of this matters much on my dev machine, but I'm intending to ultimately run it off a Raspberry Pi, so the more optimal I can get it, the better.


Update: I was not aware that str_replace worked directly on arrays, in that case, just two options then

  • Use str_replace on array
  • Implode, use str_replace on string, Explode
4
  • 2
    str_replace itself will allow you to pass an array as the subject. "If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well." php.net/str_replace Done Commented Mar 18, 2016 at 14:29
  • Oh perfect, I didn't catch that. I'll update the question then. Thanks Commented Mar 18, 2016 at 14:33
  • First off, just go with the simplest code. The performance difference is likely to be milliseconds, don't worry about. If you insist on still worrying about it, run the 1500 replacements yourself using your different methods and time it! Commented Mar 18, 2016 at 14:34
  • Great stuff @jszobody, I didn't know str_replace accepted & returned arrays! Thanks :) Commented Mar 18, 2016 at 14:38

2 Answers 2

2
$array = str_replace("_SUB_/","",$array);

http://php.net/manual/es/function.str-replace.php

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )

subject

The string or array being searched and replaced on, otherwise known as the haystack.

If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.
Sign up to request clarification or add additional context in comments.

Comments

1

As @jszobody says, str_replace will work with arrays too (something I didn't know!):

$array = str_replace("_SUB_/","",$array);

Alternatively, array_map() allows you to apply a function to each item of an array:

function replace_sub($n)
{
    return str_replace("_SUB_/", "", $str);
}
$result = array_map("replace_sub", $array);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.