So; I'm exploding a card list string, the delimiter is " ;
".
One string can, for example, be " creature;;1;;;;;1;1;;;2
".
This gives me an array with the length 5.
Another card is " creature;;3;;4;;2;3;2;
"
I need arrays with the same length and the values at the same positions, so how do I achieve this?
Basically I want the explode to make an (empty) element in the array from ";;
".
I hope you can understand my question, since it's not easy to explain!
Thanks for any help :)
patty
How is explode
NOT working for you?
php > var_dump(explode(';', 'a;;b'));
array(3) {
[0]=>
string(1) "a"
[1]=>
string(0) ""
[2]=>
string(1) "b"
}
Note that the dumped array does have 3 elements, with the second one being empty, as expected.
Its the normal behaviour of the explode function
<?php
$string = "creature;;1;;;;;1;1;;;2";
$splitted = explode(";", $string);
var_dump($splitted);
$string = "creature;;3;;4;;2;3;2;";
$splitted = explode(";", $string);
var_dump($splitted);
Output is
array(12) {
[0]=>
string(8) "creature"
[1]=>
string(0) ""
[2]=>
string(1) "1"
[3]=>
string(0) ""
[4]=>
string(0) ""
[5]=>
string(0) ""
[6]=>
string(0) ""
[7]=>
string(1) "1"
[8]=>
string(1) "1"
[9]=>
string(0) ""
[10]=>
string(0) ""
[11]=>
string(1) "2"
}
array(10) {
[0]=>
string(8) "creature"
[1]=>
string(0) ""
[2]=>
string(1) "3"
[3]=>
string(0) ""
[4]=>
string(1) "4"
[5]=>
string(0) ""
[6]=>
string(1) "2"
[7]=>
string(1) "3"
[8]=>
string(1) "2"
[9]=>
string(0) ""
}
explode
in PHP:explode
splits a string into an array by a text delimiter. This is done by taking the area of the string between two characters matching the delimiter and pushing it to an array. Thus, if there are 2 delimiters right after each other, then an empty array entry is added (as other answers have stated). This is default, expected behavour of explode
.
If you want to get rid of all empty entries, you could do something like this:
$split = explode(";","creature;;1;;;;;1;1;;;2");
$final = Array();
for ($i=0;$i<count($split);$i++) {
if ($split[$i]!="") {
array_push($final,$split[$i]);
}
}
This is a basic example of array processing, and it works like so:
explode
the string by the requested delimiter. We call the result $split
.$final
.for
loop, which iterates through every item in the array $split
.if
statement checks if the entry is blank, if it isn't, then we push the item to the array $final
.$final
only contains the elements we want.