When I add a string value into an array through array_push()
, it gives me a numeric value, i.e.,
$array = array("one", "two", "three");
$array2 = array("test", "test2");
foreach ($array as $value) {
if ($value === 'one') {
$push = array_push($array2, $value);
}
}
print_r($push);
Its output is 3
. I want $array2 = array("test", "test2", "one")
The + operator in PHP when applied to arrays does the job of array UNION. $arr += array $arr1; effectively finds the union of $arr and $arr1 and assigns the result to $arr .
The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).
When you want to add an element to the end of your array, use push(). If you need to add an element to the beginning of your array, try unshift(). And you can add arrays together using concat().
The array_push is working as it is designed for.
It will add the value and returns the number of elements in that array.
so it is natural if it is returning 3 your array has 2 elements after array push there are now three elements.
You should print_r($array2)
your array and look the elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With