1

I have an array of arrays, and I want to loop them while assigning a new key-value for each. But the original array fails to response. Here is my try:

<?php
$cards = array(
    array(
        "test" => 1  
    ),array(
        "test" => 2      
    )
);

foreach($cards as $card){
    $card["success"] = 1;
}

print_r($cards);

OUTPUT:

Array
(
    [0] => Array
        (
            [test] => 1
        )

    [1] => Array
        (
            [test] => 2
        )

)

How can I modify the method hence the 'success' value can be inserted into each of them?

2 Answers 2

3

Passing array elements by reference (notice the & sign):

foreach($cards as &$card){
    $card["success"] = 1;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use it like this. Here we are inserting value on the iteration of $key.

Try this code snippet here

<?php
ini_set('display_errors', 1);
$cards = array(
    array(
        "test" => 1  
    ),array(
        "test" => 2      
    )
);

foreach($cards as $key=> $card){
    $cards[$key]["success"] = 1;//Inserting value on the a key of $cards
}

print_r($cards);

Output:

Array
(
    [0] => Array
        (
            [test] => 1
            [success] => 1
        )

    [1] => Array
        (
            [test] => 2
            [success] => 1
        )

)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.