Arjun321
Arjun321

Reputation: 99

Simple way to replace value in array in PHP when you know the index

I have created an array in PHP of strings. While my understanding of PHP is imperfect, I believe that arrays are by default ordered by an index and I should be able to access an element of the array using: array[0] or array[1] etc. Regardless, I have created the array by explicitly creating an index with the following code employing a loop:

//create empty array container
    $myarray = "";
//create counter
    $i = 0;
//begin loop of limited size...
    $myarray[$i] = "some color...this changes with each iteration of loop";
    $i = $i + 1;
    //end loop

Note I end up with something like 1=>red,2+>blue,3+>green etc.

I know this code works because it creates an array that if I implode, gives me the string that I want e.g. redbluegreen

$arrayasstring = implode("",$myarray);//produces redbluegreen

However, I would like to access one of the values of the loop using the index and change it. For example, I might want to change $array[0] from red to purple.

 $index = 0;
    $myarray[$index] = "purple"; //does not work

What is a simple way to accomplish this?

Thanks for any suggestions.

Upvotes: 0

Views: 2280

Answers (1)

Alexandro Giles
Alexandro Giles

Reputation: 492

To initialize an Array you have to use [] or the function array:

In your example:

$myarray = array();

If you want to add a series of values with the default key assignment you only have to put in between the parenthesis: array(color1, color2, color3)

$myarray = array('blue', 'red', 'yellow')

Then you can view what is on your variable, using: print_r($myarray)

print_r($myarray)
// this will output:
Array
(
    [0] => blue
    [1] => red
    [2] => yellow
)

After this, now you can change the key => value, as you want:

$index = 0;
$myarray[$index] = "purple";
print_r($myarray);

//this will now output:
Array
(
    [0] => purple
    [1] => red
    [2] => yellow
)

And your job is done.

Observations:

  • In your question, you are using two differents arrays: $myarray and $array, you are having an error because $array[$index] is different to the first $myarray[$i] = "some color...this changes with each iteration of loop";

  • Use print_r($yourVariable) to show what is in the variable to debug what you are doing wrong.

Upvotes: 1

Related Questions