Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a string value into a PHP array

Tags:

php

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")

like image 884
souce code Avatar asked Mar 28 '11 11:03

souce code


People also ask

Does += work on arrays in PHP?

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 .

Can you add to an array in PHP?

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).

How do you add values to an array?

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().


1 Answers

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.

like image 121
Shakti Singh Avatar answered Oct 23 '22 05:10

Shakti Singh