2

Why is 'the array pushed element' not echoed?

function dofoo1() {  

    $array = array("1aaa", "2bbbb", "3cccc");  
    $count = '######';  
    $array1 = array_push($array, $count);  

    return $array1;  
}  

$foo1 = dofoo1();  
echo $foo1[3];  
jhinzmann
  • 968
  • 6
  • 15
Latestarter
  • 39
  • 1
  • 7

4 Answers4

6

No need to assign array_push to a variable.

function dofoo1() {

    $array = array("1aaa", "2bbbb", "3cccc");  
    $count = '######';  
    array_push($array, $count);  

    return $array;  
}  


$foo1 = dofoo1();  
echo $foo1[3];  
Muhammet
  • 3,288
  • 13
  • 23
2

You can simply use array merge

function dofoo1() {  
  $array = array("1aaa", "2bbbb", "3cccc");  
  $count = '######';  
  
  return array_merge($array, array($count));  
}  

$foo1 = dofoo1();  
echo $foo1[3];  
1

array_push() Returns the new number of elements in the array.

So, You should return the array itself in which you have pushed,

Change,

return $array1; 

to

return $array; 
viral
  • 3,724
  • 1
  • 18
  • 32
1

As described in the php docs array_push() alters the given array and returns only the number of elements. Therefore you have to return $array instead of $array1.

If you just want to add one element, it is even better to avoid array_push() and use $array[] = $count; instead. This usage is recommended in the docs of array_push().

So your code should look like this:

function dofoo1() {  
  $array = array("1aaa", "2bbbb", "3cccc");  
  $count = '######';  
  $array[] = $count;  

  return $array;  
}  

$foo1 = dofoo1();  
echo $foo1[3];
jhinzmann
  • 968
  • 6
  • 15