Here you will learn how to Update or Modify and Delete an array in PHP.

Update or Modify an Array in PHP

Update an element of an array

<?php
$names = ['John','Smith'];

// Updating First Array Value
$names[0] = 'Mark';

echo "<pre>";
var_dump($names);
echo "</pre>";
?>
Browser Output
array(2) {
  [0]=>
  string(4) "Mark"
  [1]=>
  string(5) "Smith"
}

Add an Element inside an Array

<?php
$names = ['John','Smith'];

// Adding new element
$names[2] = "Mark";

echo "<pre>";
var_dump($names);
echo "</pre>";
?>
Browser Output
array(3) {
  [0]=>
  string(4) "John"
  [1]=>
  string(5) "Smith"
  [2]=>
  string(4) "Mark"
}

Delete An element of an array

<?php
$var1 = array('Hello', 25);
// delete array element
unset($var1[1]);

echo "<pre>";
var_dump($var1);
echo "</pre>";
?>
Browser Output
array(1) {
  [0]=>
  string(5) "Hello"
}

Delete an Array in PHP

You can delete an array in PHP by using the unset() function.

<?php
$names = ['John','Smith'];

// Deleting Array
unset($names);

// You will get errors
echo $names[0];
echo "<br>";
echo $names[1];
?>
Browser Output
Notice: Undefined variable: names…
Notice: Undefined variable: names…

Leave a Reply

Your email address will not be published. Required fields are marked *