0

I have this code:

$postList = array();

foreach($post as $blue)
{
    $text = $string;
    $url = trim(url);

    $newPost = array(  "ID" => $counter,
                        "Text" => $text,
                        "url" => $url );
    $postList = array_merge($postList, $newPost);
    $counter += 1;
}

This code does not work and what I find into the postList array is the last post item, not the list. How do I insert all the items into the array?

Thanks in advance

1
  • Side note: the $url = trim(url) line must be a typo, url (without $) means nothing (or its a constant?) Commented Aug 6, 2014 at 9:24

3 Answers 3

2

try this

$postList = array();
$counter = 0;
foreach($post as $blue)
{
    $text = $string;
    $url = trim(url);

    $newPost = array(  "ID" => $counter,
                        "Text" => $text,
                        "url" => $url);
    $postList[] =  $newPost;
    $counter += 1;
}
Sign up to request clarification or add additional context in comments.

2 Comments

It works! Thank you very much. Could you please explain me why?
we are creating $newPost each time and assigning it to $postList array. key is autometicaly incremented by using []
0

Save creating an extra variable try:

$postList = array();

foreach($post as $blue)
{
    $text = $string;
    $url = trim(url);

    $postList[] = array(  "ID" => $counter,
                        "Text" => $text,
                        "url" => $url );
    $counter += 1;
}

Comments

0

In Object Oriented programming languages there is push method in the Array object. So it's something like this.

array.push(element);

This means push element at the end of the array. In PHP there is also push method, but it's static function, PHP libraries are like that. So you do something like this:

$persons = Array();
$person = Array('id' => 1, 'name' => 'my name');
array_push($persons, $person);

or

$array[] = $element;

The first one is more explicit and you'll understand better what it does. You should read more about data structures in PHP.

1 Comment

In PHP the array notation is $key => $value not 'key': 'value'

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.