Reputation: 61
I have the following PHP code. It iterates through an array which contains two items in item["type] and two items in item["count(*)"]
However, when I add the items to the arrays, only the last ones are added. What am I doing wrong?
$behTypes = array();
$behValues = array();
foreach($behaviours as $item){
$behTypes = $item["type"];
$behValues = intval($item["count(*)"]);
}
echo($behTypes);
echo($behValues);
Upvotes: 1
Views: 185
Reputation: 20881
To add an element to an array in PHP, use the []
syntax on the array. This syntax behaves identically with array_push()
. To quote the documentation...
array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. Has the same effect as:
<?php $array[] = $var; ?>
Here is the fix applied to your code...
$behTypes = array();
$behValues = array();
foreach($behaviours as $item){
$behTypes[] = $item["type"];
$behValues[] = intval($item["count(*)"]);
}
echo($behTypes);
echo($behValues);
Upvotes: 3
Reputation: 114
you need to push items into array.
$behTypes = array();
$behValues = array();
foreach($behaviours as $item){
array_push($behTypes, $item["type"]);
array_push($behValues, intval($item["count(*)"]));
//OR
//$behTypes[] = $item["type"];
// $behValues[] = intval($item["count(*)"]);
}
print_r($behTypes);
print_r($behValues);
Upvotes: 0
Reputation: 1
$behTypes = array();
$behValues = array();
foreach($behaviours as $item){
$behTypes[] = $item["type"];
$behValues[] = intval($item["count(*)"]);
}
echo($behTypes);
echo($behValues);
Upvotes: 0