11

I have a string which will contain a file upload name, for example "image.jpg". I'm trying to use the explode function but it's returning an error "explode() expects parameter 2 to be string, array given in..."

I've tried looking for reasons why and comparing it to how use is instructed on PHP.Net but to no avail.

$upload_extension = end(explode(".", $feature_icon));
7
  • 1
    Show us how you define $feature_icon May 11, 2013 at 14:34
  • 1
    $feature_icon should be a string, not an array.
    – FThompson
    May 11, 2013 at 14:34
  • 6
    You may want to consider pathinfo() anyway...
    – SEngstrom
    May 11, 2013 at 14:35
  • 1
    array(1) { [0]=> string(9) "image.jpg" } May 11, 2013 at 14:40
  • 1
    @user2332946 Keep in mind, that you'll need to validate the type of $_GET['feature_icon'] to string anyway. If someone posts against your page with controls named feature_icon[], it'll auto-create an array, and you'll be passing that to explode, yielding errors.
    – Dan Lugg
    May 11, 2013 at 14:46

3 Answers 3

19

you can not use end() like you are doing since

end() -> Parameters ¶ The array. This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference.

so do like

$feature_icon ="image.jpg";
$upload_extension =  explode(".", $feature_icon);
$upload_extension = end($upload_extension);
var_dump($upload_extension );

Live result

0
7

Try doing it like this separately:

 $upload_extension = explode(".", $feature_icon);
 $upload_extension = end($upload_extension);
2
  • Actually, +1 as end() expects an argument by reference; er go, not the result of a function call or literal value (for pedantry, a non-reference returning function call)
    – Dan Lugg
    May 11, 2013 at 14:43
  • 2
    I hate this strict :(
    – vp_arth
    Nov 3, 2013 at 17:32
1

I probably should know better than to reply to a years old thread, but for what it's worth:

$upload_extension = end(explode(".", $feature_icon));

(which doesn't work because end() can only accept arrays defined in a variable, not those returned by functions) can be replaced with:

$upload_extension = explode ('.', $feature_icon) [count (explode ('.', $feature_icon)) - 1];

Whether or not you find that more or less elegant than using an intermediary variable to store the array, or using two lines of code (both as suggested above) is a matter of personal preference.

1
  • I don't even remember asking this question - heck I don't even use PHP anymore, but thanks for the reply. It might be useful to others! Dec 20, 2019 at 11:10

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.