How to split hash key and value without using "foreach&

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
henka
Forum Newbie
Posts: 1
Joined: Wed Aug 02, 2006 1:19 pm

How to split hash key and value without using "foreach&

Post by henka »

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, without using "foreach ($array as $key => $val)", I want to get at the $key string of a hash.

Any ideas?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

create a function/method.
User avatar
sweatje
Forum Contributor
Posts: 277
Joined: Wed Jun 29, 2005 10:04 pm
Location: Iowa, USA

Post by sweatje »

off the top of my head:

Code: Select all

function fromArray($key, $array) { return (array_key_exists($key,$array) ? $array[$key] : $key; }
$val = fromArray('this is a really long key...',$array);
Post Reply