Darren Griffin
Darren Griffin

Reputation: 31

Use variable as php array

I want to know if variables can be used in an array. see below ($userArray = array($usersBought);)

    $user = "Darren";
    $usersBought = $row['usersBought'];
    $userArray = array($usersBought);
    if (in_array($user, $userArray)) {
      $button = "yes";
    }

If this can work, what should the text be in the database? I have tried this...

"Darren","Adam","Coral"
Darren,Adam,Coral
Darren Adam Coral

This array is in a while loop and displays multiple unordered lists on a page through the loop. That is why i have the $usersBought = $row['usersBought']; there

Upvotes: 1

Views: 99

Answers (4)

Emilio Gort
Emilio Gort

Reputation: 3470

for example: Database test, table Users

ID|Name|
1|Emilio|
2|Darren|

After the connect to DB you should do something like this:

$user = 'Darren';
$query = "SELECT Name FROM Users WHERE Name ='$user'";
$result = mysqli_query($query);
$count = mysqli_num_rows($result);
if($count >= 1){
    $button = "yes";
}

Upvotes: 0

sybear
sybear

Reputation: 7784

If you store your data like this: Darren,Adam,Coral the right solution would be:

$user = "Darren";
$usersBought = explode(",",$row['usersBought']); //Just choose the right delimiter.


if (in_array($user, $userArray)) {
  //Ok proceed.
}

Also, you may use function preg_grep that will allow you to check in case-insensitive manner.

$in_array = preg_grep("/{$user}/i" , $usersBought);

Upvotes: 3

Drew
Drew

Reputation: 4373

Assuming $row['usersBought'] is itself an array (which I doubt) then the function you are looking for is called array_merge

and your code would look like:

$userArray = array_merge($usersBought);

Upvotes: 0

Bad Wolf
Bad Wolf

Reputation: 8349

For your database to be properly normalized, you should structure your tables in such a way that you are not storing an array in the database and instead each user is a row in a table.

To answer your question however, you need to use the explode() function.

//$row['usersBought'] = "Darren,Adam,Coral"; <- Example 
$user = "Darren";
$usersBought = $row['usersBought'];
$userArray = explode(",", $usersBought);
if (in_array($user, $userArray)) {
  $button = "yes";
}

In the example above it assumes that the users are separated by commas, but you can change the first parameter to be whatever you want.

Upvotes: 3

Related Questions