John Davidson

php - Add a key and value into an array via function

0 comments
Message:


My PHP is quite basic when it comes to functions. I am trying to add a key and value pair to an already existing array via a function. 'Oranges' should also appear in the printed array. Can anyone explain what I am doing wrong?


function add_fruit($ar) {
$ar[] = 'oranges';
}

$fruits = [
'0' => 'apples',
'1' => 'pears',
'2' => 'bananas',
];

add_fruit($fruits);

print_r($fruits);


My Answer:
You are almost there! The issue is that you are not returning the modified array from the function. You need to return the modified array in order for the changes to be reflected in the original array. Here is the corrected code:

php
function add_fruit($ar) {
$ar[] = 'oranges';
return $ar;
}

$fruits = [
'0' => 'apples',
'1' => 'pears',
'2' => 'bananas',
];

$fruits = add_fruit($fruits);

print_r($fruits);


Now, when you run this code, 'oranges' will be added to the $fruits array and it will be printed out along with the other fruits.

Rate this post

5 of 5 based on 8674 votes

Comments




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