Reputation: 25
I have tried to solve it, but I am lost. Can you see my mistake?
I have something wrong with:
array_push($change_data[$y],$_POST['new']['location'][$y]);
I get error:
array_push() expects parameter 1 to be array, integer given in...
$y
is an integer but I need save it there. I need to create array:
$change_data(id => location = value)
$location_count = count($_POST['new']['id']);
$change_data=array();
for($y=0; $y<$location_count;$y++){
if (!empty($_POST['new']['location'])) {
array_push($change_data,$y);
if (!empty($_POST['new']['location'][$y])) {
array_push($change_data[$y],$_POST['new']['location'][$y]);
}
}
}
Upvotes: 2
Views: 13196
Reputation: 11942
The problem is you're dereferencing the value and then trying to use it as an array. That won't work. Because $change_data[$y]
gives us a scalar integer value, but array_push
expects an array value, not a scalar value (hence the error you're getting).
An easier way to do this is to just assign to the array directly. $change_data[] = $y
is semantically equivalent to saying array_push($change_data, $y)
.
The other issue is $change_data[$y]
may not always be what you think it is in this loop, because you're pushing to the array conditionally and $y
increments linearly. You can't chose the key with array_push
, but you can say $change_data[$y] = $y
.
Finally your loop loops awkward because it makes some assumptions about PHP Arrays that aren't true. Namely that an array key is always a numeric value, sequentially incremented from 0.
Instead, if we actually evaluate what you're trying to do here more carefully you'll find that you're just trying to use $_POST['new']['id']
and $_POST['new']['location']
as an adjacency list. The more sane way to traverse PHP arrays and traversable objects is to use the foreach
construct, which makes certain guarantees that your for
loop here, simply does not.
Here's a simpler way to write the same code, but less prone to error.
$change_data = [];
foreach(array_filter($_POST['new']['id']) as $key => $value) {
if (!empty($_POST['new']['location'][$key])) {
$change_data[$key] = $_POST['new']['location'][$key];
}
}
The difference here is that the foreach
construct guarantees that we iterate over every element in array_filter($_POST['new']['id'])
and array_filter()
guarantees that no element in that loop will be considered empty()
. Since the key is tracked by foreach
and stored in the $key
variable we make the same adjacency list assumptions and assign directly to $change_data
under the same key value.
Upvotes: 4
Reputation: 2837
When you use array_push
, it place the new element at the end of the array, you can't decide the array key
.
Thus array_push($change_data[$y],$_POST['new']['location'][$y]);
should be array_push($change_data,$_POST['new']['location'][$y]);
If you want to decide of the key, you will do this instead:
$change_data[$y]=$_POST['new']['location'][$y]);
Upvotes: 1