How to add a string value into a PHP array
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);