darrrrUC
darrrrUC

Reputation: 311

mysqli added empty value on query

Im doing a query that im trying to split into an array like this:

$sql = "SELECT *FROM questions";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$myString = $row["qID"] . "," . $row["question"] . "," . $row["answer"] . "%";
$myArray = explode('%', $myString);

print_r($myArray);
}

} else {
echo "0 results";
}
$conn->close();

but when i print the array print_r($myArray); or loop trough it my result is as follows:

Array (
    [0] => 1,Vem levde mellan 970-1022,2
    [1] =>
)
Array (
    [0] => 2,Vem levde mellan 1008-1050,3
    [1] =>
) 

why do the arrays retrieve empty values? Each array gets 2 indexes [0] and [1] but the [1] is empty. The [0] index contains the information just the way i want it but that empty index is causing me trouble.

Upvotes: 0

Views: 42

Answers (3)

Marc B
Marc B

Reputation: 360882

Just to flesh out my comment above, this is NOT mysqli doing anything:

php > $x = "a,b,c%";
php > var_dump(explode('%', $x));
array(2) {
  [0]=>
  string(5) "a,b,c"
  [1]=>
  string(0) ""
}

This is normal behavior for explode() if the delimiter being used appears at the start OR end of the string.

Upvotes: 1

venca
venca

Reputation: 1222

$myString is ending with %. Then you exlode the string by %. So expected output is array with minimally two indexes.

Upvotes: 1

codeneuss
codeneuss

Reputation: 905

The problem is that you explode at the char % and not at the char ,. I think what you need is:

$myArray = array();
while($row = $result->fetch_assoc()) 
  $myArray[] = array($row["qID"],$row["question"],$row["answer"]);

print_r($myArray);

Upvotes: 1

Related Questions