Trufa
Trufa

Reputation: 40717

array_push() one value into multiple arrays

I realize this may be a very simple question but I need to know how to add ONE value to multiple arrays in PHP. (The better way)

array_push($one, "hello");
array_push($two, "hello");

I need to do something like this (just as an example)

array_push($one && $two, "hello");

I have read through this question and seen the discussion if whether $array[] is better for speed, is it easier to use $array[] for my specific problem?

Thanks in advance!! && please ask for any clarification needed!

Upvotes: 6

Views: 3239

Answers (3)

alex
alex

Reputation: 490233

I think the best way to do it would be...

$one[] = $two[] = 'hello';

It works!

Update

BTW Any answers using array_push? – Trufa

Sure.

$value = 'hello';
array_push($one, $value);
array_push($two, $value);

Though I would say using the [] syntax is easier :)

If you want to add multiple array members, it may be easier to use array_merge().

$one = array_merge($one, array(
   'a',
   'b',
   'c'
));

You can also use the + array operaror, but it acts different (e.g. won't overwrite string keys from the left operand like array_merge() will).

$one += array(
   'a',
   'b',
   'c'
);

Upvotes: 4

Treby
Treby

Reputation: 1320

try $one[] = $two [] = "hello";

Upvotes: 2

catchdave
catchdave

Reputation: 9327

Why does it have to be on one line? The below code works and is very readable:

$value = 'hello';
$one[] = $value;
$two[] = $value;

Upvotes: 2

Related Questions