Saurabh Sharma Saurabh Sharma - 4 months ago 10
HTML Question

using rest show details

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;
}
}
}

?>




Answer

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;
    }
}