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];  
0

4 Answers 4

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];  
Sign up to request clarification or add additional context in comments.

2 Comments

It's different from one in javascript. Gracias!
@Latestarter De nada :)
2

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

Comments

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

Comments

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; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.