开发者

How to add a string value into a PHP array

开发者 https://www.devze.com 2023-02-20 01:11 出处:网络
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\");

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


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.


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


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)


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

Check http://php.net/array_push.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号