Reputation: 107
store array values in another array using for loop in php
$sql = "select id,user_email,username,full_name from registration";
$connection = Yii::app()->db;
$command = $connection->createCommand($sql);
$rows = $command->queryAll();
$email_arr = [];
for ($i=0; $i <=count($rows); $i++) {
$email_arr[] = $rows[$i]['user_email'];
}
i am getting undefined offset 39 php error anyone can help me please
Upvotes: 0
Views: 1376
Reputation: 2795
This doesn't work because you are using $i <= count($rows)
instead of $i < count($rows)
, since arrays start at 0 and the last index of an array is count - 1
.
$rows[count($rows)]
is outside the bounds of the array, which is why you are getting "undefined offset".
You can make what you're writing more maintainable by either using a foreach like:
$email_arr = [];
foreach ($rows as $row) {
$email_arr[] = $row['user_email'];
}
An arguably better way to do this would be to map the array in a functional way like:
$email_arr = array_map(function($row) {
return $row['user_email'];
}, $rows);
Upvotes: 1
Reputation: 407
Use condition as follows: use "less than" only if your array has 39 elements then array will start with 0 and end on 38 which will be 38 < 39. Array's subscript start with 0.
for ($i=0; $i < count($rows); $i++) {
$email_arr[] = $rows[$i]['user_email'];
}
Upvotes: 0