0

How do I create an empty JSON array?

I tried $finalJSON["items"][0] = ''; but that gave me {"items":[""]}

I tried $finalJSON["items"][0] = null; but that gave me {"items":[null]}

What I actually want is {"items":[]}

How to achieve this?

1
  • There is no such thing as "JSON array" (or "JSON object"). JSON is a portable text representation of some data structure. If you want to encode as JSON an empty array then create an empty array (array() or [] on PHP 5.4 and newer) and encode it using json_encode(). Commented Aug 23, 2015 at 12:30

6 Answers 6

2

Your code actually creates an array with already one element with key 0 and value '' (empty string) or null. Instead, use:

$finalJSON["items"] = array();
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

$arr['items'] = array();
echo json_encode($arr);

Comments

1

You should set an empty array:

$finalJSON = [];
$finalJSON["items"] = [];

echo json_encode($finalJSON);

Output:

{"items":[]}

Example

Comments

1

Consider this example:

<?php
$items = [];
echo json_encode($items);

The output is: [].

That is the "most empty" array you can create and convert into a json encoding.

So if you want such an array as value inside an object as property item, then use an object:

<?php
class myObject {
  public $items = [];
}
echo json_encode(new myObject);

The output is: {"items":[]}

Comments

0
$finalJSON["items"] =  []; //short syntax

or

$finalJSON["items"] =  array(); //old syntax

and to output:

echo json_encode($finalJSON);

Comments

0

This should work

<?php
$finalJSON["items"] =  array();
echo json_encode($finalJSON);
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.