0

Let me start off by saying that I am fairly new to php. I am trying to create a multidimensional array but running into a weird result when I look at the result. I have a feeling that the syntax I am using is not correct but cannot verify that anywhere online. So I am posing the question here.

Here is the gist of what I am trying to do:

// Given: $row["foo"] == "Hello" && $row["bar"] == 1

while($row = mysqli_fetch_array($query_result, MYSQLI_ASSOC)){
    $multiArray[$i] = $row["foo"];
    $multiArray[$i]["lorem"] = $row["bar"];
    $i++;   
}

When I go to print $multiArray[$i] I get: 1ello.

As I said I believe that the error lies in my syntax of how I am assigning this multidimensional array. Can someone please help me find a similar method to (what I can only guess) php madness above?

Thank you in advance!

3 Answers 3

2

You can't combine data types in a same array value.

$multiArray[$i] only can have a value type, ( string, integer, or array), but in your code, you want an array and a string at the same time !

A possible solution is ( but depends of your logic ) :

while($row = mysqli_fetch_array($query_result, MYSQLI_ASSOC)){
    $multiArray[$i]["lorem_string"] = $row["foo"];
    $multiArray[$i]["lorem"] = $row["bar"];
    $i++;   
}
Sign up to request clarification or add additional context in comments.

Comments

0

Because first you assign $multiArray[$i] = $row["foo"]; so $multiArray[$i] will be a string with an example value Hello, then you assign the string's lorem index with $multiArray[$i]["lorem"] = $row["bar"];. lorem evaulates to 0, so the output will ve 1ello

Edit: a fresh version of PHP should produce a warning too.

Comments

0

You are essentially first assigning $multiArray[$i] a string "hello", then trying to assign an array to it on the next line.

Instead you need the first assignment to be to an array, which can then contain strings or ints or more arrays or whatever

Also, doing things explicitly in this case will also help you understand what is going on.

For example:

$i = 0; // explicit initialization of $i
while($row = mysqli_fetch_array($query_result, MYSQLI_ASSOC)){
    $multiArray[$i] = array(); // explicit initialization of array
    $multiArray[$i]["foo"] = $row["foo"];
    $multiArray[$i]["lorem"] = $row["bar"];
    $i++;   
}

Then if you want "hello" echo $multiArray[$i]["foo"]; and if you want 1 echo $multiArray[$i]["lorem"];.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.