/    Sign up×
Community /Pin to ProfileBookmark

array push with key

Hi

I want to do an array_push while assigning a key to the value I push. array_push doesn’t allow that so i wrote my own.

[code=php]

function array_push_key (&$array, $key, $value) {
$array[$key] = $value;
}

[/code]

What do you guys think about it? is it usefull or is there a way to do it better

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@NogDogNov 23.2006 — Seems a bit easier to me to just type [b]$array['key'] = $value;[/b] in the first place, plus it will execute faster that way.
Copy linkTweet thisAlerts:
@pcthugNov 23.2006 — Your function allows for only one array element (i.e. one key and one value) to be pushed. Thus it renders as useless, It would be better use [I]$array[$key] = [/I] because in that way there is no overhead of calling an unneeded function.

Here is a my interpretation (not-tested). It allows multiple array elements to be passed in the form of an one-dimensional array with two separate values.

Example:
[code=php]
$my_array = array('foo' => 'bar', 'hello' => 'world');
array_push($my_array, array('pcthug', 'cool'), array('apple' => 'red'))
[/code]

<i>
</i>$my_array:

array(
['foo'] =&gt; 'bar',
['hello'] =&gt; 'world',
['pcthug'] =&gt; 'cool',
['apple'] =&gt; 'red',
);


Code:
[code=php]
function array_push_key(&$array)
{
$num = func_num_args();

if($num < 2)
return trigger_error('Insufficient number of arguments passed.', E_USER_WARNING);

global $array;

for($int = 1; $int <= $num; $int++)
{
$arg = func_get_arg($int)

if(!is_array($arg) || count($arg) < 2)
continue;

$array[$arg[0]] = $arg[1];
}
}
[/code]
Copy linkTweet thisAlerts:
@bokehNov 23.2006 — [code=php]

function array_push_key (&$array, $key, $value) {
$array[$key] = $value;
}

[/code]
[/QUOTE]
If you like that function the following will be right up your street too.
[code=php]function MyEcho($input)
{
echo $input;
}[/code]

How to use it:[code=php]MyEcho($input);[/code]Or how about this: [code=php]function MyReturn($input)
{
return $input;
}[/code]
In use you will be able to nest that:[code=php]$input = MyReturn(MyReturn(MyReturn(MyReturn(MyReturn($input)))));[/code]
×

Success!

Help @stephan_gerlach spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...