Guilherme Silva
Guilherme Silva

Reputation: 41

I'm doing a preg_split but only obtaining a value on the second value of the array - PHP

Whith this code I'm trying to split a string in the "//" but it only gives me a value on the $splits[1] and on the $splits[0] gives me nothing.

while($row = $result->fetch_assoc()) {
        $amigos[] = $row["Id2"]."//".$row["ID"];
    }

    foreach ($amigos as $i => $value) {
        $splits = preg_split("//", $value);
        $IDAmizade = $splits[0];
        $IDAmigo = $splits[1];
        $sql = "SELECT `Nome`,`Agrupamento` FROM `Users` WHERE `ID`='$IDAmigo'";
        $result = $conn->query($sql);
        $row = $result->fetch_assoc();
        echo($row["Nome"] . "+" . $row["Agrupamento"] . "+". $IDAmizade . "/");
    }

And yes the $_row["Id2"] is returning a number i've confirm that.

The string that i'm trying to split is like: "1//3" and after the split it gives me splits[0] is nothing and splits[1] is 3

what am I doing wrong?

Upvotes: 1

Views: 494

Answers (3)

Toto
Toto

Reputation: 91385

As said in comment, why do you have 2 loops? A single one is enough and you don't need to split a string:

while($row = $result->fetch_assoc()) {
    $sql = "SELECT `Nome`,`Agrupamento` FROM `Users` WHERE `ID`='" . $row["ID"] . "'";
    $result2 = $conn->query($sql);
    $row2 = $result2->fetch_assoc();
    echo($row2["Nome"] . "+" . $row2["Agrupamento"] . "+". $row["Id2"] . "/");
}

Moreover you'd better use a JOIN instead of doing a second SELECT in the loop. I can't say more because we don't know the schema of the database and what is the database.

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163217

The reason the 0 index is empty is because when using preg_split in this part preg_split("//", the first argument is the regex which uses / as a delimiter so you are splitting the string on an empty string.

$pattern = "//";
$string = "1//3";
print_r(preg_split($pattern, $string));

Output

Array
(
    [0] => 
    [1] => 1
    [2] => /
    [3] => /
    [4] => 3
    [5] => 
)

If you want to use preg_split with / as a delimiter and split on // you have to escape the forward slash.

$pattern = "/\/\//";

If you would use another delimiter like ~ the pattern would look like

$pattern = "~//~";

As already pointed out, you could use explode instead

$string = "1//3";
print_r(explode("//", $string));

Output

Array
(
    [0] => 1
    [1] => 3
)

Upvotes: 1

CountKyle
CountKyle

Reputation: 458

You need to change your preg_split pattern. What you're doing at the moment will split the string up into its component characters.

So

$splits = preg_split("//", $value);

Should be:

$splits = preg_split("[//]", $value);

See more about preg_split here, and more about regular expressions here.

Alternatively, you could use explode, which splits a string by another string.

$splits = explode("//", $value);

Upvotes: 0

Related Questions