Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding key-value pair to array conditionally adds the key with a null value to the array

I am working on an api that requires a json script, but I am making it so I can use the api on my website.

The issue I am stuck on and struggling to find an answer for is when the array is ‘compiled’.

If one of my form inputs are null, I want that key-value pair to be non-existent rather than just making the value null.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My current script:

if (isset($_POST['title']) || isset($_POST['description']) || isset($_POST['image-url'])) {
    $embed = TRUE;
} else {
    $embed = FALSE;
}

$data_arr = array("username" => $_POST['username']);

if (isset($_POST['usericon'])) {
    $data_arr["avatar_url"] = $_POST['usericon'];
}

if (isset($_POST['tts']) && $_POST['tts'] == "true") {
    $data_arr["tts"] = $_POST['tts'];
} else {
    $data_arr["tts"] = "false";
}

if (isset($_POST['content'])) {
    $data_arr["content"] = $_POST['content'];
}

if (isset($_POST['file'])) {
    $data_arr["file"] = $_POST['file'];
}

$data_arr["type"] = "rich";

if ($embed) {
    $data_arr["embeds"] = array();

    $embed = array();

    if (isset($_POST['author-name'])) {
        $author = array("name" => $_POST['author-name']);

        if (isset($_POST['author-url'])) {
            $author["url"] = $_POST['author-url'];
        }

        if (isset($_POST['author-icon'])) {
            $author["icon_url"] = $_POST['author-icon'];
        }

        $embed["author"] = $author;
    }

    if (isset($_POST['title'])) {
        $embed["title"] = $_POST['title'];
    }

    if (isset($_POST['title-url'])) {
        $embed["url"] = $_POST['title-url'];
    }

    if (isset($_POST['description'])) {
        $embed["description"] = $_POST['description'];
    }

    if (isset($_POST['color']) && $_POST['color'] != "#000000") {
        $embed["color"] = ltrim($_POST['color'], '#');
    }

    if (isset($_POST['thumbnail-url'])) {
        $embed["thumbnail"] = array("url" => $_POST['thumbnail-url']);
    }

    if (isset($_POST['image-url'])) {
        $embed["image"] = array("url" => $_POST['image-url']);
    }

    if (isset($_POST['footer-txt'])) {
        $footer = array("text" => $_POST['footer-txt']);

        if (isset($_POST['footer-icon-url'])) {
            $footer["icon_url"] = $_POST['footer-icon-url'];
        }

        $embed["footer"] = $footer;
    }

    if (isset($_POST['timestamp']) && $_POST['timestamp'] == 1) {
        $embed["timestamp"] = date("c", strtotime("now"));
    }

    $data_arr["embeds"][] = $embed;
}

var_dump($data_arr);

Output:

array(7) { ["username"]=> string(12) "DS_Announcer" ["avatar_url"]=> string(0) "" ["tts"]=> string(5) "false" ["content"]=> string(4) "test" ["file"]=> string(0) "" ["type"]=> string(4) "rich" ["embeds"]=> array(1) { [0]=> array(7) { ["author"]=> array(3) { ["name"]=> string(0) "" ["url"]=> string(0) "" ["icon_url"]=> string(0) "" } ["title"]=> string(0) "" ["url"]=> string(0) "" ["description"]=> string(0) "" ["thumbnail"]=> array(1) { ["url"]=> string(0) "" } ["image"]=> array(1) { ["url"]=> string(0) "" } ["footer"]=> array(2) { ["text"]=> string(0) "" ["icon_url"]=> string(0) "" } } } }

Readable version:

array(7) { 
    ["username"]=> string(12) "DS_Announcer" 
    ["avatar_url"]=> string(0) "" 
    ["tts"]=> string(5) "false" 
    ["content"]=> string(4) "test" 
    ["file"]=> string(0) "" 
    ["type"]=> string(4) "rich" 
    ["embeds"]=> array(1) { 
        [0]=> array(7) { 
            ["author"]=> array(3) { 
                ["name"]=> string(0) "" 
                ["url"]=> string(0) "" 
                ["icon_url"]=> string(0) "" 
            } 
            ["title"]=> string(0) "" 
            ["url"]=> string(0) "" 
            ["description"]=> string(0) "" 
            ["thumbnail"]=> array(1) { 
                ["url"]=> string(0) "" 
            } 
            ["image"]=> array(1) { 
                ["url"]=> string(0) "" 
            } 
            ["footer"]=> array(2) { 
                ["text"]=> string(0) "" 
                ["icon_url"]=> string(0) "" 
            } 
        } 
    } 
}

Which in turn in the json script echo $json_data = json_encode($data_arr, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);:

{"username":"DS_Announcer","avatar_url":"","tts":"false","content":"test","file":"","type":"rich","embeds":[{"author":{"name":"","url":"","icon_url":""},"title":"","url":"","description":"","thumbnail":{"url":""},"image":{"url":""},"footer":{"text":"","icon_url":""}}]}{"embeds": ["0"]}

Readable:

{
  "username":"DS_Announcer",
  "avatar_url":"",
  "tts":"false",
  "content":"test",
  "file":"",
  "type":"rich",
  "embeds":[
    {
      "author":{
        "name":"",
        "url":"",
        "icon_url":""
      },
      "title":"",
      "url":"",
      "description":"",
      "thumbnail":{
        "url":""
      },
      "image":{
        "url":""
      },
      "footer":{
        "text":"",
        "icon_url":""
      }
    }
  ]
}{"embeds": ["0"]}

"{"embeds": ["0"]}" is not there when everything is working OR I have embed inputs filled

The values I have set in this example are:

  • "username" => "DS_Announcer"
  • "content" => "test"
  • "type" => "rich"

The goal in this thread is to figure out a way to make it so the if statements determine if even the key will be added to the array. As it stands now, if statements add the key with a null value that makes it so the json script being encoded cannot be read by the application reading it (Which I’m sure most have already noticed it’s a custom discord webhook api).

I appreciate any help in the matter.

>Solution :

If you want to remove only empty values, you can go recursevly trough the array and unset the values

$array = [
    "username" => "DS_Announcer",
    "avatar_url" => "",
    "tts" => "false",
    "content" => "test",
    "file" => "",
    "type" => "rich",
    "embeds" => [
        [
            "author" => [
                "name" => "alex",
                "url" => "",
                "icon_url" => ""
            ],
            "title" => "",
            "url" => "",
            "description" => "",
            "thumbnail" => [
                "url" => ""
            ],
            "image" => [
                "url" => ""
            ],
            "footer" => [
                "text" => "",
                "icon_url" => ""
            ]
        ]
    ]
];

// Function to recursively remove keys with null values
function removeEmptyKeys(&$array)
{
    foreach ($array as $key => &$value) {
        if (is_array($value)) {
            removeNullKeys($value);
            if (empty($value)) {
                unset($array[$key]);
            }
        } elseif (empty($value)) {
            unset($array[$key]);
        }
    }
}

removeEmptyKeys($array);

$json = json_encode($array); // will equal {"username":"DS_Announcer","tts":"false","content":"test","type":"rich","embeds":[{"author":{"name":"alex"}}]}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading