-1

How to change or update array value in PHP through array number?

Example:

$array1 = array("cat","dog","mouse","dog");

I want to change the value of dog in the 2nd array only

Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
Nikko Dela Cruz
  • 52
  • 2
  • 10

4 Answers4

0

Edit :-

To delete element use unset(arrayVar[key])

For eg :- unset($array1[1]) - will delete the "mouse" at key/index 1 if you wish to delete 2nd occurance then use unset($array1[3])

Original :-

Explain your problem in more detail please !

What do you mean by 2nd array and where exactly is it ?

Do you mean to edit the 2nd occurance of "dog" in array ? If so then it would be $array1[3]="someNewValue"

Harsh Gundecha
  • 1,053
  • 9
  • 16
0

Use Variable variables:

$a = 'array' . '1';
$$a[1] = 'doggg'; #value changed
$b = 'array' . '2';
$$b[1] = 'newDogg'; #value changed
AmirHossein
  • 3,281
  • 23
  • 25
0

if you want to remove 2 index then

$array1 = array('dog','mouse','cat','mouse');
 unset($array1[1]);
 print_r($array1);

Output

Array ( [0] => dog [2] => cat [3] => mouse ) 

//if you are looking for remvoing duplicate value then you can use array_unique

$result=array_unique($array1);

print_r($result);

Output

Array ( [0] => dog [1] => mouse [2] => cat )
Vision Coderz
  • 7,644
  • 5
  • 36
  • 56
0

If you mean you have to remove an element from an array, probably this will help.

array_splice( $array1, OFFSET, 1 );

replace OFFSET with the index you want to remove.

HariV
  • 639
  • 1
  • 9
  • 17