John Davidson

add an element with value to an array in php

0 comments
Message:


i have this code with missing part and the output:


<?php
$months = array('four'=>'April', 'five'=>'May');
Missing#6;
Missing#7;
echo $months['nine']."<br>";
echo $months['ten'];
?>

The output:


**September


October**


and since it has two lines missing, I tried doing



<?php
$months = array('four'=>'April', 'five'=>'May');
$months[] = array('nine'=>'september');
$months = array('ten'=>'october');
echo $months['nine'], "\n";
echo $months['ten'];
?>

but in the compiler only print October and an error for nine:


PHP Notice: Undefined index: nine in 1784341836/source.php on line 5



My Answer:
To add an element with a value to an array in PHP, you can use the following code:

php
$months = array('four'=>'April', 'five'=>'May');
$months['nine'] = 'September';
$months['ten'] = 'October';
echo $months['nine']. "
";
echo $months['ten'];
?>


This code will output:

September
October


By using the `$months['nine'] = 'September';` and `$months['ten'] = 'October';` lines, you are adding the elements 'nine' and 'ten' with their respective values to the `$months` array.

Rate this post

5 of 5 based on 5124 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us