Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
PHP json_encode creates number index as string instead of an object

I have the following example code in PHP:

$data = array(
 'hello',
 'world',
 'hi'
);

$ret = array();
$ret['test'] = array();
$ret['testing'] = array();

foreach($data as $index => $value){
  if($index < 1){
      $ret['test'][$index]['val'] = $value;
      $ret['test'][$index]['me'] = 'index < 1';
  }
  else {
      $ret['testing'][$index]['val'] = $value;
      $ret['testing'][$index]['me'] = 'index >= 1';
  }
}

echo json_encode($ret);

I would expect this to be the JSON output:

[{
  "test":[
    {
       "val": "hello",
       "me": "index < 1"
    }
  ],
  "testing":[
    {
       "val": "world",
       "me": "index >= 1"   
    },
    {
       "val": "hi",
       "me": "index >= 1"
    }
  ]
}]

However, what ends up happening is that I end up with the following:

[{
  "test":[
    {
       "val": "hello",
       "me": "index < 1"
    }
  ],
  "testing":{
    "1":{
       "val": "world",
       "me": "index >= 1"   
    },
    "2":{
       "val": "hi",
       "me": "index >= 1"
    }
  }
}]

The "1" and "2" keys appear despite being an int and despite the correct rendering of test when the same counter variable is used. Is there a way I can make sure that testing becomes an array of JSON objects?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Because the array doesn't start with index 0 but with index 1, it's encoded as an JSON object instead of an JSON array.

You can use the array_values() function to remove the indexes and only keep the values.

Example:

$ret['testing'] = array_values($ret['testing'])
echo json_encode($ret);

But because you don't need the index at this moment, you can also refactor your code to this:

foreach($data as $index => $value){
  if($index < 1){
    $ret['test'][] = array(
      'val' => $value,
      'me' => 'index < 1'
    );
  }
  else {
    $ret['testing'][] = array(
      'val' => $value,
      'me' => 'index >= 1'
    );
  }
}
echo json_encode($ret);

This way, the arrays will always start with index 0.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!