1

I am having a brain fart on this one because I can't figure out how to get this count to return as expected :

$ajax_result['data'] = array('ID' => 0, 'Timestamp' => $_POST['end_date'] * 1000, 'Total' => 0);

echo count($ajax_result['data']);

The above returns 3 - I am expecting it to return 1 or would like it to (1 array in the array). $ajax_result['data'] can possibly contain many arrays and that is the total I need to get.

The format of this needs to stay the same because these results are used by a plugin that needs them in this format.

2
  • You’re counting the number of elements in the array: ID, Timestamp, and Total. Perhaps you’re looking for is_array($ajax_result['data'])? Commented Dec 30, 2020 at 23:45
  • on re-reading your question, you are mistaken on a point: 'data' will not contain many arrays. It might very well contain an array of arrays though. So the question is how can you distinguish between the two? And frankly, this doesn’t even make sense... why not use [0] for a single instance? You’ve got some serious technical debt here. Commented Dec 31, 2020 at 0:05

1 Answer 1

1

To get your desired result (and probably to have your code work correctly anyway), you need to make $ajax_result['data'] a multi-dimensional array:

$ajax_result['data'] = array(array('ID' => 0, 'Timestamp' => $_POST['end_date'] * 1000, 'Total' => 0));

count($ajax_result['data']) will now return 1.

Then you can push new values into the array e.g.:

$ajax_result['data'][] = array('ID' => 1, 'Timestamp' => $_POST['end_date'] * 1000, 'Total' => 2);

Demo on 3v4l.org

Sign up to request clarification or add additional context in comments.

3 Comments

$ajax_result['data'][] = ... this is part of a switch statement and in every single other one I have the ending [] on this variable... except for this one. That is all I was missing and kept looking over it. Thanks for pointing this out! I thought I was going crazy.
You're definitely right about that. It wouldn't be the first time and I'm sure won't be the last :) These are the ones that drive you nuts then you can only laugh about it after.
@user756659 yup, been there, done that! :)

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.