Array built in a loop only retains the last encountered value

I have created 2 array, I'm trying to show my first array to another array. So I used foreach statement so I can show each value in my 2nd array like this

$first = array(
    '12:00 AM',
    '1:00 AM',
    '2:00 AM',
    '3:00 AM',
    '4:00 AM',
    '5:00 AM',
    '6:00 AM',
    '7:00 AM',
    '8:00 AM',
    '9:00 AM',
    '10:00 AM',
    '11:00 AM'
);

$2nd = array('body' =>array(),);

foreach ($first as $value) {
    $2nd['body'] = $value;
}

echo json_encode($2nd); ?>

The problem is only the 11:AM is showing.

Upvotes: 1

Views: 808

Answers (4)

swidmann
swidmann

Reputation: 2792

First: you can't start a variable name with a number (PHP Docs), and second you need to append ( added [] ) the value to the array, otherwise you will only get the last value.

$first = array( '12:00 AM', '1:00 AM', '2:00 AM', '3:00 AM', '4:00 AM', '5:00 AM', '6:00 AM', '7:00 AM', '8:00 AM', '9:00 AM', '10:00 AM', '11:00 AM' );

$second= array( 'body' => array(), );

foreach ( $first as $value ) {
    $second['body'][] = $value;
}

echo json_encode($second);

You could also use a shorter way:

$first = array( '12:00 AM', '1:00 AM', '2:00 AM', '3:00 AM', '4:00 AM', '5:00 AM', '6:00 AM', '7:00 AM', '8:00 AM', '9:00 AM', '10:00 AM', '11:00 AM' );

$second = array( 'body' =>  $first );

echo json_encode( $second );

Upvotes: 2

user4962466
user4962466

Reputation:

You can use the = php equal operator

$first = array( '12:00 AM', '1:00 AM', '2:00 AM', '3:00 AM', '4:00 AM', '5:00 AM', '6:00 AM', '7:00 AM', '8:00 AM', '9:00 AM', '10:00 AM', '11:00 AM' );

$second['body'] = $first;

print json_encode($second);

Tip: variable names cannot start with a digit, so rename the $2nd to $second http://php.net/manual/en/language.variables.basics.php

Here working sample https://eval.in/443545

Upvotes: 1

flowit
flowit

Reputation: 1442

You don't append your values from $first to $second['body'] but overwrite them. Either use the array_push function or $second['body'][] = $value; Edit: And yes, of course, respect the variable naming rules as already said in the other answers.

Upvotes: 0

oreopot
oreopot

Reputation: 3450

Change variable name. (i.e) cannot begin with digit. Consider using it as $second

$first = array( '12:00 AM', '1:00 AM', '2:00 AM', '3:00 AM', '4:00 AM', '5:00 AM', '6:00 AM', '7:00 AM', '8:00 AM', '9:00 AM', '10:00 AM', '11:00 AM' );   

$second= array( 'body' => array(), );
foreach ( $first as $value ) 
    {
     $second['body'][] = $value;
    }
 echo json_encode($second);

Upvotes: 0

Related Questions