-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
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Nikko Dela Cruz
  • 42
  • 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,139
  • 9
  • 16
0

Use Variable variables:

$a = 'array' . '1';
$$a[1] = 'doggg'; #value changed
$b = 'array' . '2';
$$b[1] = 'newDogg'; #value changed
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
  • 8,257
  • 5
  • 41
  • 57
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
  • 687
  • 1
  • 10
  • 17