Reputation: 13
I am having a bit of trouble with this PHP code. I am not sure why it is printing Array
8 times. From what I see, it should be printing the contents of the array
The goal is to declare an array, using a global
, define the array, assign it to another array and display the entire array.
$car_array = array( );
$array = array( );
create_array_cars ();
displayProduct ($array);
function create_array_cars ( ) {
global $car_array;
$car_array = array( );
$car_array[] = "ID: 12345" ;
$car_array[] = "ID: 45678" ;
$car_array[] = "ID: 67890" ;
$car_array[] = "ID: 89123" ;
return $car_array;
}
function displayProduct ($array) {
global $array;
for ($i=0;$i<4;$i++) {
print "$array<br>"; }
}
$array = create_array_cars();
print (displayProduct($array));
Upvotes: 0
Views: 132
Reputation: 6393
function displayProduct ($array) {
foreach ($array as $val) {
print $val."<br>"; }
}
Upvotes: 1
Reputation: 57
$car_array = array( );
$array = array( );
create_array_cars ();
displayProduct ($array);
function create_array_cars () {
$car_array = array( );
$car_array[] = "ID: 12345" ;
$car_array[] = "ID: 45678" ;
$car_array[] = "ID: 67890" ;
$car_array[] = "ID: 89123" ;
return $car_array;
}
function displayProduct ($array) {
//global $array;
print_r( $array);
echo "<bR>";
}
$array = create_array_cars();
displayProduct($array);
not use global. and print "$array
" is not correct... remove this " ".
or use print_r($VAR)
Upvotes: -2
Reputation: 76646
Store the return value of the function in a variable:
$array = create_array_cars();
displayProduct($array);
create_array_cars()
returns an array — you need to store it in a variable for later use. displayProduct();
takes an array as its argument and displays the contents inside it. Besides, it doesn't return a value — so we don't need to store the return value.
Stop using global
s when you don't need it:
Globals are generally considered to be a bad coding style. You really don't want it here. Your function doesn't even need to deal with external data. You're only creating an array, inside the function, and returning it. So your code can just be:
function create_array_cars() {
// Create the array
$car_array = array(
"ID: 12345",
"ID: 45678",
"ID: 67890",
"ID: 89123"
);
// Return it
return $car_array;
}
Print the array values instead of trying to display an entire array:
Printing any array always prints Array
. You need to pick individual values in the array — since you're using a for
loop which operates on the basis of numeric indices, you can do that with $array[$i]
.
Also, I've changed $i < 4
to $i < count($array)
. This makes your code more dynamic. It'll work even if there are more than 4 elements in the array (not in this case though, as you're manually returning a pre-defined array in the other function).
The modified function will look like:
function displayProduct($array) {
for ($i = 0; $i < count($array); $i++) {
print $array[$i] . "<br />";
}
}
Upvotes: 1