1

I need to check some key value is exist in an array using PHP. Here is my code:

$comment = json_encode(array(array('day_id' => '1', 'comment' => 'vodka0'),array('day_id' => '', 'comment' => ''), array('day_id' => '3', 'comment' => 'vodka3'),array('day_id'=>'4','comment'=>'hytt')));
$arrComment = json_decode($comment, true);

Here I need to check some day_id key has value or all day_id key has blank value.

3 Answers 3

1

Use array_column and array_filter to check this:

// extract all day_id columns
$dayId = array_column($arrComment, 'day_id');
// filter the empty values
$filtered = array_filter($dayId);

if (empty($filtered)) {
  echo "All Day Ids are empty.";
}
else {
  echo "Some or all of them have some value.";
}
Sign up to request clarification or add additional context in comments.

Comments

0

Do you mean this: var_dump(array_column($arrComment, 'day_id'));

It returns all values of day_id key. Now do what you want.

2 Comments

I need to check this inside if...else statement.
Ok above code will provide you array of day_id values. Now filter your array with $someVar = array_filter($values). array_filter() removes empty value. If all are empty $someVar variable will be empty. Hope you got your answer. I can give you idea and you get your hints. Now write your code. You'll get expected output. Happy coding.
0
for ($i = 0; $i < count($arrComment); $i++) {
    if (isset($arrComment[$i]['day_id'])) {
        //value is set
    } else {
        //value is not set
    }
}

1 Comment

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.