Home > Blockchain >  check dynamic key is not empty in php
check dynamic key is not empty in php

Time:10-21

I have array like this

$groupData = [
    [
        "Text Field Two" => "Value 1 Row 1",
        "" => "Value 2 Row 1",      //empty/missing key name
        "" => "Value 3 Row 1",      //empty/missing key name
        "JL" => ""                  //empty/missing value
    ],
    [
        "Text Field Two" => "Value 1 Row 2",
        "Justice League" => "Value 2 Row 2",
        "" => "Value 3 Row 2",      //empty/missing key name
        "" => "Value 4 Row 2"       //empty/missing key name
     ]
];

I want to check the key of an array is empty/missing so I can show message otherwise I wanna manipulate the array. In above array some keys are empty/missing.

foreach($groupData as $key => $value) {
    if(empty($value['emptykey'])) {
        return message/error
    } else {
        further code process here
    }
}

But the problem is the keys are dynamic and can't get the key name static to check if they are empty/missing.

If anyhow I get all the key name dynamically in loop so I also want to check their value too.

CodePudding user response:

It is a bit unclear to me what you are expecting and where the keys come from, BUT:

When using the same key in 1 array, you will loose all the values, except the latter one. SO, looking at your array:

$groupData = [
    [
        "Text Field Two"=> "Value 1 Row 1",
        ""=> "Value 2 Row 2",
        ""=> "Value 3 Row 3",
        "JL"=> "Value 4 Row 3"
    ],
    [
        "Text Field Two"=> "Value 1 Row 2",
        "Justice League"=> "Value 2 Row 2",
        ""=> "Value 3 Row 2",
        ""=> "Value 4 Row 2"
     ]
];

Will effectively result in:

array(2) {
  [0]=>
  array(3) {
    ["Text Field Two"]=>    string(13) "Value 1 Row 1"
    [""]=>                  string(13) "Value 3 Row 3"
    ["JL"]=>                string(13) "Value 4 Row 3"
  }
  [1]=>
  array(3) {
    ["Text Field Two"]=>    string(13) "Value 1 Row 2"
    ["Justice League"]=>    string(13) "Value 2 Row 2"
    [""]=>                  string(13) "Value 4 Row 2"
  }
}

So with that in mind, could you rephrase your question?

CodePudding user response:

foreach($groupData as $key => $value) {
    foreach($groupData as $nk=> $nv) {
     if(empty($nk)){
        return //error
     }
    }
}
  • Related