Yasitha
Yasitha

Reputation: 911

How to check whether a value exists in an array php

Can I check for a value in an array?

What I mean is if I'm having an array like this

$image=array(
    1 =>$_FILES['image1']['name'],
    2 =>$_FILES['image2']['name'],
    3 =>$_FILES['image3']['name'],
    4 =>$_FILES['image4']['name'],
    5 =>$_FILES['image5']['name'],
    6 =>$_FILES['image6']['name'],
);

I want to know what are the keys that have an image name and I want to update some columns of a mysql table according to array key number, those are having an image name.

I also want to write a sql query to do this. (this is an example of what I want. I know this query is wrong)

$query="
    UPDATE mytablename
    foreach($image as $valeu){
        echo'$image(1)=$value';
        echo'$image(2)=$value';
        echo'$image(3)=$value';
        echo'$image(4)=$value';
        echo'$image(5)=$value';
        echo'$image(6)=$value';
    }
";

Upvotes: 1

Views: 205

Answers (4)

Yasitha
Yasitha

Reputation: 911

i made my own way to do this.

$image=array(
1 =>$_FILES['image1']['name'],
2 =>$_FILES['image2']['name'],
3 =>$_FILES['image3']['name'],
4 =>$_FILES['image4']['name'],
5 =>$_FILES['image5']['name'],
6 =>$_FILES['image6']['name'],
);
$i=1;
    $sql  = "UPDATE salehotel ";
    $sql .="SET"." ";
foreach($image as $value){
    if(!$value==""){    
    $sql .=  "`image".$i."`"."="."'". $value ."'".",". " ";
    $i++;
    }

}

$sql .="
      `name`='$name',
      `status`='$status',
      `type`='$type',
      `location`='$location',
      `price`='$price',
      `description`='$description'
    WHERE  
      `property_id`='$edit'
      ";

this is a very simple way but it does my work. thank you all

Upvotes: 0

Tarun
Tarun

Reputation: 3165

you can do like this,

foreach($image as $key=>$imgInfo)
{
   if(isset($imgInfo['name']))
   {
      $validKeys = $key.',';
   }
}
$validKeys = rtrim($validKeys,',');

Upvotes: 2

Fluffeh
Fluffeh

Reputation: 33542

By the looks of things, if a key exists in your array, it has an image attached to it?

As for the query you can use an implode to get the names of the files like this:

    $query="
    update myTableName 
    set someValue=1 
        where imageName in (".implode($image).")";

Or if you need to get the array keys, then you might have to do a loop first:

$IDArray=array();
foreach($image as $key => $val)
{
    $IDArray[]=$key;
}

$query="
    update myTableName 
    set someValue=1 
        where imageID in (".implode($IDArray).")";

Upvotes: 2

PiTheNumber
PiTheNumber

Reputation: 23562

array_search is your friend:

$key = array_search($image_name, $image);

http://www.php.net/manual/en/function.array-search.php

When ever you do something with arrays read the list of array functions.

Upvotes: 4

Related Questions