Reputation: 3
I am using the following code:
$row_arr=$_POST['row_driver'];
print_r($row_arr);
returns:
Array ( [0] => d1 [1] => d2 [2] => d3 [3] => d5 )
but
echo count($row_arr);
is returning me a value of
1
Any reason why?
Here row_driver is an array being received through a form from a previous PHP page using hidden element property of HTML form. Also,
foreach($row_arr as $driver)
{
//code here
}
is returning:
Warning: Invalid argument supplied for foreach() in D:\XAMPP\htdocs\Carpool\booking_feed.php on line 36
Upvotes: 0
Views: 1540
Reputation: 647
The problem lies with the hidden field
foreach ($rows as $value){
<input type="hidden" name="row_driver[]" value="<?php echo $value; ?>">
}
Upvotes: 0
Reputation: 22427
expression
The expression to be printed. return If you would like to capture the output of print_r(), use the return parameter. When this parameter is set to TRUE, print_r() will
return the information rather than print it.
Return Values
If given a string, integer or float, the value itself will be printed. If given an array, values will be presented in a format that shows keys and elements. Similar notation is used for objects.
When the return parameter is TRUE, this function will return a string. Otherwise, the return value is TRUE.
print_r()
can use as special printing method to display all values in arrays and for associative arrays(more helpful for this).
Associative array:
Associative arrays are arrays that use named keys that you assign to them.
If you use echo
you have print it with a array index. As a example $row_arr[0]
or if you use for associative array instead of index, key is used. it may be string.
Upvotes: 0
Reputation: 311
You might just store the count value in some variable :
$row_arr=Array('d1','d2','d3','d4');
print_r($row_arr);
$count = count($row_arr);
echo 'Your Count is:- '.$count;
Upvotes: 1
Reputation: 2347
The issue you are facing is with the fact that $_POST['row_driver']
is not an array.
If you have one hidden HTML input:
<input type="hidden" name="row_driver" value="<?php print_r($rows); ?>">
...then $_POST['row_driver']
would be a string, e.g.:
$_POST['row_driver'] = "Array ( [0] => d1 [1] => d2 [2] => d3 [3] => d5 )";
, and therefore, your count()
function results in 1.
This would also explain the second issue you are facing, with foreach()
, where the function expects an array, but you are providing a string.
A solution would be to use a foreach loop for your hidden HTML inputs like this:
<?php foreach($rows as $row_driver){?>
<input type="hidden" name="row_driver[]" value="<?php echo $row_driver; ?>"/>
<?php }?>
This would then turn your $_POST['row_driver']
into an array.
Upvotes: 1