0

Im stuck with this simple problem in php:

$words = array();
while ($allrow = mysqli_fetch_array($all))
{       
    $words = "".utf8_encode($allrow["eng"])."" => "".$allrow["id"]."";                  
}

foreach ($words[] as $key => $word) {

I wanna have an array with some words and its id. In the foreach loop I need to be able to know which id each word has.

3 Answers 3

2

You array building syntax is off, try this:

// array key is the id, swap if needed, but I assume the ids are unique
$words[$allrow["id"]] = utf8_encode($allrow["eng"]);

Every time you say $words = $anything, you are overwriting the last iteration.

This should have generated a parse error:

."" => "".

Not sure how that slipped by your testing. No need for the empty "" strings either.

Sign up to request clarification or add additional context in comments.

Comments

1

Inside your foreach loop, add each entry to the array.

$words[utf8_encode($allrow["eng"])] = $allrow["id"];

if you actually want the id as the key, which is more probable, you reverse the assignment:

$words[$allrow["id"]] = utf8_encode($allrow["eng"]);

As well, you should not iterate using $words[]. That does not make sense. Use
foreach($words as $key => $value)

As assigning array values with [] and iterating arrays are basic concepts, you should study up on PHP arrays before trying to use them.

1 Comment

I didn't even look at that last bit, this code is a mess. +1 for recommended reading on basic php.
0
$words[$allrow["id"]] = utf8_encode($allrow["eng"]);

and then in the foreach loop use foreach ($words as $key => $word) {

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.