0

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

2
  • your problem is in $i <=count($rows), it should be just < (less than) that's because the indexing start from zero, which meanse the 39th element is with index 38. Commented May 3, 2016 at 11:09
  • yeah it's working now.. thank you.... Commented May 3, 2016 at 11:12

3 Answers 3

1

for ($i=0; $i < count($rows); $i++) {

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

2 Comments

Hi! Code only answers rarely provide much insight, please elaborate what you changed / why your code works and why OP's didn't.
well technically there is a change in the logic of the for loop @PiyushGupta
1

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);

Comments

0

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'];
   }

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.