1

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??

Dharman
  • 26,923
  • 21
  • 73
  • 125
TusharD
  • 21
  • 4

3 Answers3

1

= is the assignment operator. If you want to check for equality, you should use the == operator (or better yet, === to avoid type juggling shenanigans):

foreach ($books as $book=>$price) {
    if ($book == $find) {
        // Here^
        echo $book;
        echo $price;
        return $price;
        break;
    }
}
Mureinik
  • 277,661
  • 50
  • 283
  • 320
0

please change the line

 if ($book=$find) {

to

 if ($book==$find) {
Ken Lee
  • 4,601
  • 3
  • 7
  • 24
0

Change if ($book=$find) to if ($book == $find). You're using the assignment operator (=) instead of a comparison operator (== or ===).

Ro Achterberg
  • 2,337
  • 2
  • 17
  • 17