0

I am using Yii, and I want to print an index of an array, but I get an error that the index is undefined, here is my code:

 $criteria = new CDbCriteria;
 $criteria->select = 'username, password'; // select fields which you want in output
 $u = Users::model()->findAll($criteria);

 foreach($u as $u)
        $users["$u->username"] = "$u->password";

echo $users['a'];

I printed the array and make sure that a index is exist, so what is the problem here?

3
  • 2
    var_dump your array and see what indexes are there. Also ($u as $u) is BAAAD idea. Commented Aug 24, 2014 at 19:02
  • nothing to solve here, the index a was stored in the the db with w space so it is ` a`, I think I need to visit the ophthalmologist. Commented Aug 24, 2014 at 19:18
  • i would clean up the db and input functions then, but you can use trim() to just clean it up here... Commented Aug 24, 2014 at 19:21

2 Answers 2

3

When using foreach() you must first specify the array you want to iterate over ($u in this case) and and a different variable after "as" to indicate the variable it should be known as within the scope of the foreach() loop. You must also declare $users to be an array so that you can add items to it. You do not need double quotes when using it is an index or array value.

// create $users array to store values
$users = array();
// iterate over the $u array referring to elements as $user
foreach ( $u as $user ){
    // place properties of $user into the $users array
    $users[$user->username] = $user->password;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this

$criteria = new CDbCriteria;
$criteria->select = 'username, password'; 
$u = Users::model()->findAll($criteria);

foreach($u as $val){
    $users["$val->username"] = "$val->password";
}
print_r($users);

2 Comments

You think that db query returns field value as an index?
Please provide a description of your answer and not just code.

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.