Syntax error How to delete an array element based on key in PHP?

How to delete an array element based on key in PHP?



To delete an array element based on a key in PHP, the code is as follows−

Example

 Live Demo

<?php
   $arr = array( " John ", "Jacob ", " Tom ", " Tim ");
   echo "Array with leading and trailing whitespaces...
";    foreach( $arr as $value ) {       echo "Value = $value
";    }    echo "
Comma separated list...
";    print_r(implode(', ', $arr));    $result = array_map('trim', $arr);    echo "
Updated Array...
";    foreach( $result as $value ) {       echo "Value = $value
";    }    unset($result[1]);    echo "
Updated Array...
";    foreach( $result as $value ) {       echo "Value = $value
";    } ?>

Output

This will produce the following output−

Array with leading and trailing whitespaces...
Value = John
Value = Jacob
Value = Tom
Value = Tim
Comma separated list...
John , Jacob , Tom , Tim
Updated Array...
Value = John
Value = Jacob
Value = Tom
Value = Tim
Updated Array...
Value = John
Value = Tom
Value = Tim

Example

Let us now see another example −

 Live Demo

<?php
   $marks = array(
      "kevin" => array (
         "physics" => 95,
         "maths" => 90,
      ),
      "ryan" => array (
         "physics" => 92,
         "maths" => 97,
      ),
   );
   echo "Marks for kevin in physics : " ;
   echo $marks['kevin']['physics'] . "
";    echo "Marks for ryan in maths : ";    echo $marks['ryan']['maths'] . "
";    unset($marks["ryan"]);    echo "Marks for ryan in maths : ";    echo $marks['ryan']['maths'] . "
"; ?>

Output

This will produce the following output. Now, an error would be visible since we deleted the element and trying to access it−

Marks for kevin in physics : 95
Marks for ryan in maths : 97
Marks for ryan in maths :
PHP Notice: Undefined index: ryan in /home/cg/root/6985034/main.php on line 25
Updated on: 2019-12-27T07:30:56+05:30

756 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements