souce code
souce code

Reputation: 675

How to add a string value into a PHP array

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

Upvotes: 11

Views: 81496

Answers (7)

ii iml0sto1
ii iml0sto1

Reputation: 1742

In more modern days you could add strings or other data types to an array with Square Bracket method like this:

$arr = ['hello'];
$arr[] = 'world';

This approach will add the string 'world' to the $arr array variable.

Now the array will actually look like this ['hello', 'world'] which is pretty neat, and quicker than array_push

array_push would be more suitable if you were to push more than one element into the array.

Im pretty confident that Square Bracket Method was introduced in PHP 5.4

Upvotes: 1

Kirby Todd
Kirby Todd

Reputation: 11556

You are printing the return value of array_push which is the number of items in the array after the push. Try this:

<?php

$array = array("one","two","three");
$array2 = array("test","test2");

foreach ($array as $value) {
    if ($value === 'one') {
       array_push($array2, $value);
    }
}

print_r($array2);

Upvotes: 7

Phoenix
Phoenix

Reputation: 4536

Really, you should be using $array2[] = $value; which will put the value in the first available numeric key in the array, rather than array_push().

To get the value of the last element in the array(i.e. what you just added) and keep the array intact, use end($array), or to get the last element and remove it from array, use array_pop($array)

Upvotes: 4

Belinda
Belinda

Reputation: 1231

array_push takes the array by reference and returns the new number of elements in the array, not the new array as described here. That is why you are getting 3. If you want to see the elements in the array use printr($array2);

Upvotes: 0

Sony Santos
Sony Santos

Reputation: 5545

array_push modifies $array2. $push contains count($array2).

Check http://php.net/array_push.

Upvotes: 1

mauris
mauris

Reputation: 43619

This line:

$push = array_push($array2, $value);

Should be just

array_push($array2, $value);

array_push() uses reference to the array for the first parameter. When you print_r(), you print the array $array2, instead of $push.

Upvotes: 8

Shakti Singh
Shakti Singh

Reputation: 86406

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.

Upvotes: 14

Related Questions