Martin
Martin

Reputation: 557

Extracting the key of a JSON string in PHP

Am working on a project whereby am parsing some data from the frontend to the backend API which is in the form of a JSON string. I want to convert the JSON string to a PHP object array then extract the key

Sample JSON string am getting

$jsonString = "{"25100978569":null}"

My PHP logic

$array = json_decode($jsonString, true);

Upvotes: 0

Views: 70

Answers (2)

Shivendra Singh
Shivendra Singh

Reputation: 3006

You can use the array_keys to get the key of array.

    <?php

$jsonString = '{"25100978569":null}';


$array = json_decode($jsonString, true);

$key = array_keys($array);


echo implode(',', $key);
?>

Upvotes: 1

You can get the first key like this:

<?php

$jsonString = "{\"25100978569\":null}";

$array = json_decode($jsonString, true);

reset($array);
$first_key = key($array);

echo $first_key;

If you are using php 7.3 or above you can use the array_key_first() function

Upvotes: 1

Related Questions