1

In my PHP, I have the following Array..

$json = array(
 "ack" => "success",
 "totalPages" => $total_pages,
 "currentPage" => $pageno,
 "results" => array()
);

I go through an array, increment a counter. Where I would return my encoded json, I add the counter into the $json array.

echo $counter //returns the number
array_push($json['count'], $counter) //returns null

How can I push the $counter into the 'count' object?

2
  • $json['count'] = $counter; echo $json['count']; ? Commented Sep 2, 2020 at 20:58
  • where is $counter set to a value? If it is not, it will be null Commented Sep 2, 2020 at 20:58

3 Answers 3

2

I'm assuming that $counter would be an integer variable, instead of an array. array_push() takes an array for the first parameter, and the additional values to add to that array.

In your case, it looks like you're wanting to set the array's key for count to the variable $counter, which you can do like so:

$json = array(
  'ack' => 'success',
  'totalPages' => $total_pages,
  'currentPage' => $pageno,
  'results' => array(),
  'count' => 0,
);

$json['count'] = $counter;

Edit:

Additionally, if you're setting the variable above for your response, and you're not doing any further code changes, you can just declare your $json array with the $counter variable, similar to how you have for totalPages and currentPage, and for completeness:

$json = array(
  'ack' => 'success',
  'totalPages' => $total_pages,
  'currentPage' => $pageno,
  'results' => array(),
  'count' => $counter, // Set the $counter variable here, straight away!
);
Sign up to request clarification or add additional context in comments.

Comments

2

To update (or set) an array key you would not use array_push(), but simply:

$json['count'] = $counter;

1 Comment

Thank you Ron, very helpful
0

no need array_push for this situation, you should do as follows


$json = array(
 "ack" => "success",
 "totalPages" => $total_pages,
 "currentPage" => $pageno,
 "results" => array()
);

$json['count']=$counter;

print_r($json); //print array for humans and see

if you use array_push in other scenarios u can use as such

for example , $array[]="item";

$array=[];
$array[]="foo";
$array[]="bar";


print_r($array); //["foo","bar"]

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.