Page 1 of 1
How do I concatenate values into an array in php
Posted: Sat Mar 28, 2009 5:31 pm
by phpnitemare
Hello,
I have an array set up currently,
$_SESSION['cart'] = 30;
$cart = $_SESSION['cart'];
Is it possible to add another value to the array separated by a comma e.g.
$cart = $cart + ',' + '$newValue
In addition, would there be a way to extract the values by using the comma as the separator to signal an additional value?
eg,
count = 0;
loop whilst items in the array {
$item = ,"$cart";
count++;
}
Many thanks for your help
Re: How do I concatenate values into an array in php
Posted: Sat Mar 28, 2009 6:36 pm
by requinix
Just use another array as the $cart/$_SESSION[cart] value.
Code: Select all
$cart = array(30);
$cart[] = $newvalue;
$_SESSION["cart"] = $cart;
Re: How do I concatenate values into an array in php
Posted: Sat Mar 28, 2009 10:18 pm
by tech603
Here is another way,
$cart += $newvalue;
This will add the values to the current array.
hope that helps.
Re: How do I concatenate values into an array in php
Posted: Sat Mar 28, 2009 10:37 pm
by requinix
tech603 wrote:Here is another way,
$cart += $newvalue;
Umm, no. Only if $cart and $newvalue are arrays or numbers.
Not for strings, not if $cart is an array and $newvalue isn't.
Re: How do I concatenate values into an array in php
Posted: Sun Mar 29, 2009 12:14 am
by tech603
Umm, no. Only if $cart and $newvalue are arrays or numbers.
Not for strings,
Umm Yes
Actually you can do this with Strings, i have done it not only in php but other languages.
not if $cart is an array and $newvalue isn't
Now this on the other hand, i missed that $cart was already set as an array.
Re: How do I concatenate values into an array in php
Posted: Sun Mar 29, 2009 12:43 am
by requinix
I'm assuming PHP 5 because it's been a long time since 5 was introduced and 4 was discontinued. So yes, if you're running PHP 4 you may get different results but I really don't think so.
Code: Select all
// remember: $a += $b is exactly the same as $a = $a + $b
$a = 1; $b = 2;
var_dump($a + $b); // int(3)
$a = 1; $b = "2";
var_dump($a + $b); // int(3)
$a = "1"; $b = 2;
var_dump($a + $b); // int(3)
$a = "1"; $b = "2";
var_dump($a + $b); // int(3)
$a = 1; $b = array(2);
var_dump($a + $b); // fatal error: unsupported operand types
$a = array(1); $b = 2;
var_dump($a + $b); // fatal error: unsupported operand types
$a = array(1); $b = array(2);
var_dump($a + $b); // array(0 => int(1))
$a = array(0 => 1); $b = array(1 => 2);
var_dump($a + $b); // array(0 => int(1), 1 => int(2))
tech603 wrote:Now this on the other hand, i missed that $cart was already set as an array.
I was saying "not if $cart is an array" generically, I didn't mean that it actually
was an array. In OP's code it wasn't, in mine it was.