Struggling Developer
Struggling Developer

Reputation: 295

add extra values from other variable in php

I have two valriables in

$a="1:2:3";
$b="1:3:4:5";

Is there any simple method to add 4 and 5 in variable $a. Means i want the value of variable to be

$a="1:2:3:4:5"

Upvotes: 1

Views: 74

Answers (4)

Ivan Buttinoni
Ivan Buttinoni

Reputation: 4145

I notice that $a is ordered, so you can apply sort to the new array

$sort = SORT_NUMERIC;
$a = implode(':',array_uniqe(array_merge(explode(':',$a),explode(':',$b)),$sort));

See array_unique to other possible sorts.

Upvotes: 0

Jan Jakeš
Jan Jakeš

Reputation: 2669

A one line solution:

$result = implode(':', array_unique(array_merge(explode(':', $a), explode(':', $b))));

An even shorter one would be:

$result = implode(':', array_unique(array_merge(explode(':', "$a:$b"))));

Upvotes: 3

Pragnesh Chauhan
Pragnesh Chauhan

Reputation: 8476

try this

$a="1:2:3";
$b="1:3:4:5";

$a = explode(':', $a);
$b = explode(':', $b);

$c = array_unique(array_merge($a,$b));

$a = implode(':', $c);

echo $a;

Upvotes: 0

Soosh
Soosh

Reputation: 812

$a2 = explode(":" , $a);
$b2 = explode(":" , $b);

foreach($b2 as $val)
{
    if(in_array($val , $a2))
        //do what you want
}

Upvotes: 0

Related Questions