TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   General (http://www.talkphp.com/general/)
-   -   Altering array data (http://www.talkphp.com/general/2810-altering-array-data.html)

benton 05-16-2008 03:59 AM

Altering array data
 
I have a multi array like
PHP Code:

 Array
(
    [
name] => Array
        (
            [
0] => text A
            
[10] => text B
        
)

    [
description] => Array
        (
            [
0] => text C
            
[10] => text D
        
)


I need to be able to change the text. I tried the following but it didn't work. I know (think) it is because it is working on a copy of the data but I can't see how to get around that. Would someone please point out where I am going wrong?
PHP Code:

  foreach ($myarray as $key)
  {
    foreach (
$key as $k => $d)
    {
      
$d 'new text';      
    } 
  } 


xenon 05-16-2008 07:48 PM

Anything but objects are passed through value instead of reference in PHP. That's why you can't do what you try to. A workaround would be:

PHP Code:

foreach($some_array as $idx => $val)
{
    
$some_array[$idx] = 'new value';



benton 05-17-2008 03:15 AM

Thanks for the reply. I had played around with that but doesn't that mean I would have to name each item in the array, something like this
PHP Code:

foreach($some_array as $idx => $val)
{
    
$some_array[$idx][0] = 'new value';
    
$some_array[$idx][10] = 'new value';


I was hoping there would be a more generic way to do it since that is going to cause problems as the code grows and changes.

Kalle 05-17-2008 05:43 AM

You mean something like:

PHP Code:

foreach($some_array as $key => $value)
{
    foreach(
$value as $index => $text)
    {
        
$some_array[$key][$index] = 'new text';
    }


?

benton 05-18-2008 11:42 AM

Yes, that does it. My thanks to both of you for your help. It is appreciated. :)

Salathe 05-18-2008 01:42 PM

You can also make sure that the array items are passed by reference (rather than by value as default) when iterating through the foreach blocks.

PHP Code:

foreach ($myarray as &$item)
{
    foreach (
$item as &$value)
    {
        
$value 'new text';
    }




All times are GMT. The time now is 05:20 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0