samedi 5 décembre 2020

PHP giving same output for different inputs

I am trying to create a simple demonstration of web services where I retrieve price of book. But here when I try different book names it gives price of 1st book entered in array.

<?php 

function get_price($find){

    $books=array(
        "c"=>20,
        "java"=>30,
        "php"=>40

    );
    foreach ($books as $book=>$price) {
        if ($book=$find) {
            echo $book;
            echo $price;
            return $price;
            break;
        }
    }

}
?>

Here, if I enter 'java' it gives price of 'c'.

<?php 

//process client req
header("Content-Type:application/json");
include("functions.php");
if (!empty($_GET['name'])) {
    # code...
    $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
{
    //throw error
    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;

}
?>

Can anyone help??




Aucun commentaire:

Enregistrer un commentaire