Reputation: 51
using rest want to show the details about the items but there is a bug in the function code but according to me that is right but there is error in 7th line. i have two code they are as follow index.php
<?php
header("content-Type:application/json");
include("function.php");
if(!empty($_GET['name'])){
$name = $_GET['name'];
$price = get_price($name);
if(empty($price))
deliver_response(200,"book not found",NULL);
else
deliver_response(200,"book found",price);
}
else{
deliver_response(400,"invalid",NULL);
}
function deliver_response($status,$status_message,$data)
{
header("HTTP/1.1 $status $status_message");
$response['status']=$status;
$response['status_message']=$status_message;
$response['data']=$data;
$json_response=json_encode($response);
echo $json_response;
}
?>
the function code
<?php
function get_price($find)
{
$books = array(
"java" => 300,
"c" => 250,
"php" => 350);
for($books as $book => $price) {
if($books == $find) {
return $price;
break;
}
}
}
?>
Upvotes: 1
Views: 50
Reputation: 1750
Use a foreach loop instead of a for loop and $book instead of $books in your if statement.
foreach ( $books AS $book => $price ) {
if ( $book == $find ) {
return $price;
}
}
Upvotes: 1
Reputation: 34914
You need to change here, change books
to book
if($book==$find)
{
return $price;
break;
}
Also change foreach
instead of for
its foreach
syntax check this manual : http://php.net/manual/en/control-structures.foreach.php
Upvotes: 2
Reputation: 23010
You need to use a foreach
loop, not a for
loop. And you don't need break, as it will never reach it. Also, books
inside the loop need to be book
, or else you're comparing to the array, not the key.
foreach($books as $book => $price) {
if($book == $find) {
return $price;
}
}
Upvotes: 2