-1

I am wondering how I can conditionally either have an array element or not at all using the following style. I realise in a general sense to do this would be trivial... So What I would really like is to be able to not have a particular element at all based on some condition, so far I can make it one value or another.

The actual motivation behind my question is to conditionally show or not show an [ActionColumn][1] in Yii2. But am more curious in a general sense now.

Thanks!

<?php
$middle_name = "James";
$full_name = [
    'Robert',
    (!empty($middle_name)) ? $middle_name : 'NA',
    'Fischer',
];
?>
4
  • Can't do it with this syntax. Place a if after that will include this information if a condition is met, or modify $middle_name to 'NA' beforehand. Commented Dec 4, 2016 at 5:56
  • @Havenard Thanks for the feedback, I wondered if that was the case. Do you see it as a language limitation, or as something you should not be trying to do in that manner? Commented Dec 4, 2016 at 6:35
  • @johnsnails, write a function or a class Commented Dec 4, 2016 at 8:31
  • 1
    It's not a language limitation, it's just semantics. If you are telling PHP to insert 3 elements in the array, all 3 elements will exist in the array even if a condition defines one as null. The inline condition has to return something, it cannot result as void. You can instead make a condition to define the array as 2 or 3 elements depending on the content of $middle_name, or you can simply insert $middle_name there and then use array_filter() to remove empty elements from the array. Commented Dec 4, 2016 at 15:40

1 Answer 1

0

Try this

<?php
    $middle_name = "James";
    $full_name[] = 'Robert';

    if ($middle_name == '' || $middle_name == null) {
        $full_name[] = 'NA';
    } else {
        $full_name[] = $middle_name;
    }

    $full_name[] = 'Fischer';
?>
Sign up to request clarification or add additional context in comments.

2 Comments

Was aware of this type of approach, but it is not entirely suitable the way I am actually setting elements as it is an array inside another array. But aware of the general approach you are referring too.
Could you add this to your question, then I can help with it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.