1

I am making a web application, I am trying to use a foreach loop and I have run into some problems.

Example

$arr = array(
   'username' => 'Test',
   'password' => 'Cheese',
);
foreach($arr as $arr2){
    echo $arr2['username'];
}

That will output this:

Warning: Illegal string offset 'username' in PATH on line 8 T

Warning: Illegal string offset 'username' in PATH on line 8 C

Does anyone know how to fix this issue.

0

2 Answers 2

1

The array you have described does not really warrant a foreach loop. You can simply do:

echo $arr['username'];

If your intention is to loop through all the different bits of data, then you can do this:

foreach ($arr as $key => $value) {
  echo $key . ': ' . $value . '<BR>';
}

Which will output something like:

username: Test
password: Cheese

More info on PHP's manual page for arrays

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

Comments

0
<?php
$arr = array(
'username' => 'Test',
'password' => 'Cheese',
);
echo $arr['username'];
echo $arr['password'];
?>

does not require foreach

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.