0

Im trying to insert variables to the array by using foreach loop. This is the foreach loop im trying to implement with

foreach($rows as &$url) {
      $link = array("url");
      array_push($url, "hello World"); 
}

And this is the result I get.

Array
(
    [0] => Array
        (
            [cat_id] => 1
            [id] => RT
            [name] => root
            [parent] => 0
            [0] => hello World
        )

    [1] => Array
        (
            [cat_id] => 2
            [id] => CI
            [name] => Civil & Interior Works
            [parent] => 1
            [0] => hello World
        )

)

but i would like the result to be like this.

Array
(
    [0] => Array
        (
            [cat_id] => 1
            [id] => RT
            [name] => root
            [parent] => 0
            [url] => hello World
        )

    [1] => Array
        (
            [cat_id] => 2
            [id] => CI
            [name] => Civil & Interior Works
            [parent] => 1
            [url] => hello World
        )

)

If i pass the variable $link = array("url"); to array_push($link, "hello World"); nothing happens.

if I remove the referance from the foreach($rows as &$url) the loop does not work at all. Please advise.

1 Answer 1

5

Just add a value under the required key:

foreach($rows as &$row) {
    $row['url'] = "hello World";
}
Sign up to request clarification or add additional context in comments.

4 Comments

thanks that worked... so array_push was not required ??
array_push adds an element in the end of array, it doesn't care about keys. If you need a specific key - use ['key'] syntax.
I noticed something... if i use &$row referance ... I lose one loop... the last element item inserted dis not picked up.
Create an example of your code and ask a new question.

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.