-5

I am facing a strange problem in array_push function of php.

Lets see my code:

$sets_collection=array();
foreach($result['ques'] as $val){
    $sets_collection=array_push($sets_collection,$val['set']);
}

It gives me the error:

Message: array_push() expects parameter 1 to be array, integer given

But when I do this, it works fine:

$sets_collection=array();
$i=0;
foreach($result['ques'] as $val)
{
    $sets_collection[$i]=$val['set']; 
    $i++;
}

Why does this happen? Is it necessary that there should be a index of an array than we can perform the push operation? Because in my first case the array $set_collection does not have an index.

2
  • 4
    RTFM for array_push, see its return value and read the examples. Commented Nov 19, 2012 at 13:33
  • 1
    syntax error ! $sets_collection[]=$val['set'] is same as array_push($sets_collection,$val['set']) ,and array_push returns new array count. After 1st iteration you will see the error in case 1. Commented Nov 19, 2012 at 13:42

4 Answers 4

2

Try this

$sets_collection=array();

foreach($result['ques'] as $val){
    array_push($sets_collection,$val['set']); 
}
Sign up to request clarification or add additional context in comments.

3 Comments

i tried same in my 1st case ,this gave me error.
No i got now my mistake,this works fine...Thanks:(
Looks like a less elegant form of array_column().
2

That's because array_push() returns the new number of elements inside the array. You don't assign the returned value to the array variable. The first parameter is actually passed by reference. Thus, its value is mutated by the function.

Comments

2

This is because array_push returns new number of elements in the array, when you pushes the array in first iteration it works but in second iteration $sets_collection becomes 1 which is an integer so the function fails with the mentioned error.

Reference: array_push()

Comments

0

array_push does not return an array - just an integer. Perhaps as the variable sets_collection is presumed to have changed to an integer because of the expected return of array_push, the subsequent parameter is also treated as an integer.

Just remove the assignment, and it should work fine.

array_push($sets_collection,$val['set']);

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.