0

I have a PHP array, actually a MySQL row constructed with CodeIgniter's Active Record.

So I have an array which var_dumps like this :

array (size=10)
  0 => 
    array (size=4)
      'user_id' => string '2' (length=1)
      'puzzle_id' => string '17' (length=2)
      'birth' => string '2014-01-26 16:08:25' (length=19)
  1 => 
    array (size=4)
      'user_id' => string '2' (length=1)
      'puzzle_id' => string '16' (length=2)
      'birth' => string '2014-01-26 02:07:05' (length=19)
  2 => .....

this is constructed like this :

$this->db->order_by("birth" , "desc");
$rows = $this->db->get("my_table" , $limit)->result_array();        
foreach($rows as $row)
{
    $row['testindex'] = "testvalue";
}
return $rows;

so why does my array NOT have the "testindex" indices ?

Thanks for any help !

3 Answers 3

2

Because that's not how PHP and foreach() in particular works.

$row in your code is a copy of the corresponding element in $rows, not the actual element. Modifying a copy doesn't modify the original.

You'd want to do this:

for ($i = 0, $c = count($rows); $i < $c; $i++)
{
    $rows[$i]['testindex'] = 'testvalue';
}
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, I always thought that foreach implicitly does that for me. Thanks for your answer! It both solved my problem, and tought me how to catch a fish :) Accepting in few minutes.
@CengizFrostclaw If this solution solves your problem, then accept it.
0

Try this (PHP 5+):

foreach($rows as &$row)
{
    $row['testindex'] = "testvalue";
}

1 Comment

Thanks, but my web server has an older PHP.
0

I think I can do this with foreach too.

Like this :

foreach($rows as $key => $value)
{
  $rows[$key]['testindex'] = "testvalue";
}

5 Comments

Yes, you could. But $value is something you don't need here.
You are right, however, there are two unnecessary variables $i and $c in the for loop. And I like the look of a foreach better. Less code and more readability. Thanks for your answer though !
They are not unnecessary. :)
Neither is $value , since it allows me to write shorter and prettier code :)
That's where you're wrong. :) Anyway, I'm not here to argue with you ... if that's what you want to use - it's your choice.

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.