Why does explode on null return 1 element?
explode expects only a string as a second parameter, and you give it some weird params. As the function name states — it «explodes» a string into an array using a delimiter you provide.
NULL might return as false and because false or in this case 0 has a length of 1, it returns that amount.
2 Answers 2
explode takes a string as its second argument, by specification. You gave it a null , so before the logic of explode runs, PHP converts the null into a string. Every function operates this way: if the arguments don’t match the formal specification, PHP attempts to «type juggle» until they do. If PHP can juggle, the engine motors along happily, otherwise you get a weak slap on the wrist:
PHP Warning: explode() expects parameter 2 to be string, object given in file.php on line 1
The way PHP juggles null to string is simple: null := » . So a call with null and a call with » are semantically equivalent because of type juggling, as seen here:
$a = explode(',', ''); $b = explode(',', null); var_dump($a === $b); // true $a = count(explode(',', '')); $b = count(explode(',', null)); var_dump($a === $b); // true
So now you might ask: why does PHP return a one-element array when exploding on an empty string? That is also by specification:
If delimiter contains a value that is not contained in string . an array containing string will be returned.
Функция explode не работает
Вы можете опубликовать сообщение сейчас, а зарегистрироваться позже. Если у вас есть аккаунт, войдите в него для написания от своего имени.
Примечание: вашему сообщению потребуется утверждение модератора, прежде чем оно станет доступным.
Обсуждения
Всем привет, нужно было написать хтмл код для онлайн шопа где прописывалось бы время когда можно забрать товар. сразу скажу с кодом я даже не на ВЫ. Этот код мне сделал чатжопати и все вроде бы работает кроме скрипта с выходными. Если сегодня (после 16 часов) или завтра один отпускных дней, то должна выплюнуться дата след. свободного дня. Но он как то этот момент игрнорирует. Заранее благодарю!
Versandtermin
Angestrebter Versand- / Abholtermin:
!DOCTYPE>
http://htmlbook.ru/html/area на одной картинке можно организовать несколько областей ссылок ведущих на разные страницы
margin внутри таблицы не работает, кста еще можно вот так реализовать так заливка ячеек будет корректно работать, если она нужна будет
row 1 cell 1 | row 1 cell 2 | row 1 cell 3 must contain several lines |
row 2 cell 1 | row 2 cell 2 | |
row 3 cell 1 | row 3 cell 2 | |
row 4 cell 1 | row 4 cell 2 | |
row 5 cell 1 | row 5 cell 2 | row 5 cell 3 |
row 6 cell 1 | row 6 cell 2 | row 5 cell 3 |
если не критично еще можно использовать обертку внутри ячеек, и с ней много чего можно дополнительного реализовать в таблицах
Switch74 Спасибо, второй вариант как раз то, что хотелось. Не понятно только, почему margin-top не работает, пробовал задавать и для клеточек, и для всей строки. А про padding как-то не подумал.
Using end() with explode() does not work
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));
@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.
3 Answers 3
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.
$feature_icon ="image.jpg"; $upload_extension = explode(".", $feature_icon); $upload_extension = end($upload_extension); var_dump($upload_extension );
Try doing it like this separately:
$upload_extension = explode(".", $feature_icon); $upload_extension = end($upload_extension);
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)
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.
Почему не работает explode?
Почему не работает explode?
Всем привет! Подскажите, почему не работает функция explode. У нас есть массив $config.
Почему explode разбивает лишнее? Как разбить по абзацам?
<?php $text='<p>абзац1</p> не абзац <p>абзац2</p>’; $pieces =.
Некорректно работает Explode
Написал код $dbplaylist = $db->query("SELECT * FROM musicbase ORDER BY id DESC"); .
Почему смена текста работает только один раз? Что неправильно в коде и почему?
Нужно чтобы при щелчке мыши на поверхности кнопки текст метки Label изменялся на текст окна.
Сообщение от sash
Сообщение было отмечено skapunker как решение
Решение
У тебя кавычки должны быть » а не ‘
$texts = explode("\r\n", $text_file);
Сообщение от xakmika
Почему выводится в виде таблицы и почему не работает сортировка
почему выводится в виде таблицы? почему не работает сортировка? и как туда можно вставить классы.
Объясните, пожалуйста, почему так происходит в первом варианте и почему второй вариант работает корректно?
Я сидел и изучал списки и операции над ними. И написал вот такой простенький код: .
explode
Этот код вычисляет сколько тебе лет по дате и времени рождения <?php $m = 1; $d = 4; .
Explode
Подскажите 1. как получить данные если могут быть два разделителя ? пример .
explode и GROUP_CONCAT
У меня есть запрос который работает с GROUP_CONCAT function top()< $this->DB =.
Функция explode();
Всем привет, как можно с помощью этой функции (explode()) разбить на массив не стирая делимитр ? То.
implode and explode
Подскажите, как работает explode? Что-то не понял как. Вот implode объеденяет элементы в массив.