Using end() with explode() does not work
Solution 1
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 );
Solution 2
Try doing it like this separately:
$upload_extension = explode(".", $feature_icon);
$upload_extension = end($upload_extension);
Solution 3
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.
DorianHuxley
Updated on June 07, 2022Comments
-
DorianHuxley almost 2 years
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));
-
Adrien Lacroix about 11 yearsShow us how you define
$feature_icon
-
FThompson about 11 years
$feature_icon
should be a string, not an array. -
SEngstrom about 11 yearsYou may want to consider pathinfo() anyway...
-
DorianHuxley about 11 years$feature_icon is just a string of the name a file has been uploaded. It's a simple $feature_icon = $_GET['feature_icon'];
-
Adrien Lacroix about 11 years@user2332946, can you show us the result of a
var_dump($_GET['feature_icon']);
? -
DorianHuxley about 11 yearsarray(1) { [0]=> string(9) "image.jpg" }
-
Dan Lugg about 11 years@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 namedfeature_icon[]
, it'll auto-create an array, and you'll be passing that to explode, yielding errors.
-
-
Dan Lugg about 11 yearsActually, +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) -
vp_arth over 10 yearsI hate this strict :(
-
DorianHuxley over 4 yearsI 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!