Apologies for cross-board post - the previous was on incorrect board (I know I risk a bludgeoning :o ).

I just can't see the obvious here, so forgive the question if it seems silly.

Given the following:

$array['keyval'] = "some data";

Is there a shorter way of coding this expression:

$val = $array['keyval'] ? $array['keyval'] : 'keyval';

The above may seem quite short already, but my code uses some rather long 'keyval' strings, eg:

$val = $array['this is a rather long string...'] ? $array['this is a rather long string...'] : 'this is a rather long string...';

In other words, if the array element value is non-null, then return the value, else return the key string.

Any ideas?

    Can you not do something like this?

    <?
    foreach( $array as $key => $value ) {
    	$val = $array[$key] ? $array[$key] : $key;
    }
    ?>
    
      benbox wrote:

      Can you not do something like this?

      <?
      foreach( $array as $key => $value ) {
      	$val = $array[$key] ? $array[$key] : $key;
      }
      ?>
      

      Thanks for the response, benbox.

      I had thought of that, but that's going to involve more coding. These hash references are used throughout a page, so I need some kind of shortcut that doesn't involve the foreach.

        In other words, a short-cut method of accessing the key and value without using "foreach".

        Sorry - I reread my post and this wasn't clear.

          Resolved - simply call a function (as suggested by others elsewhere):

          function fromArray($key, $array)
          { return ($array[$key] ? $array[$key] : $key); }
          
            Write a Reply...