0

I'm using array_push method to get all the integers into array as follows.

$response = json_decode($jsonResponse);
 foreach($response as $item) { //foreach element in $response
     $type = $item; 
     $unique_id = $type->id;
     $id_array=array();
     array_push($id_array, $unique_id);     
 }  
 var_dump($id_array);

But the $id_array contains only last integer element. Is there any wrong with above code or can't we push integer elements into php array?

2
  • You are resetting the array by initializing it in the loop. Take it out of the loop Commented Dec 8, 2016 at 10:15
  • @Rishi Oh no. Got the point. Thanks Commented Dec 8, 2016 at 10:18

3 Answers 3

3

Put $id_array=array(); at the beginning of foreach

$response = json_decode($jsonResponse);
  $id_array=array();
  foreach($response as $item) { //foreach element in $response
      $type = $item; 
      $unique_id = $type->id;
      array_push($id_array, $unique_id);     
  }  
 var_dump($id_array);

You can Minimize Code inside foreach

$response = json_decode($jsonResponse);
$id_array=array();
foreach($response as $item) { //foreach element in $response
    $unique_id = $item->id;
    array_push($id_array, $unique_id);     
}  
var_dump($id_array);

OR

$response = json_decode($jsonResponse);
$id_array=array();
foreach($response as $item) { //foreach element in $response
  array_push($id_array, $item->id);     
}  
var_dump($id_array);
Sign up to request clarification or add additional context in comments.

1 Comment

Or it's just array_push($id_array, $item->id);
1

Initialize the array outside the loop :

$response = json_decode($jsonResponse);
$id_array = array();
foreach($response as $item) { //foreach element in $response
    $type = $item; 
    $unique_id = $type->id;
    array_push($id_array, $unique_id);     
}  

Comments

1
$response = json_decode($jsonResponse);
$id_array=array();
foreach($response as $item) { //foreach element in $response
   $type = $item; 
   $unique_id = $type->id;
   array_push($id_array, $unique_id);     
}  
var_dump($id_array);

This should work..

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.