Jump to content

Help with array


tqla

Recommended Posts

Hello. I have an array called $subzz that looks like this

 

array(3) {
  [0]=>
  string(1) "3"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "1"
}

 

I can echo any of the values like this: echo $subzz['2']

 

But what I am trying to do is look at each value and change another variable accordingly.

 

For example:

 

if $subzz['2'] equals 1 then $var = 100

if $subzz['1'] equals 2 then $var = 50

if $subzz['0'] equals 2 then $var = 5

 

I suspect I need to use a loop of some kind but I am failing to figure out how to do it.

 

Can someone show me how to tackle this? Thanks.

Link to comment
https://forums.phpfreaks.com/topic/226715-help-with-array/
Share on other sites

I will do that ultimately but the array will change dynamically depending on who is logged in.

 

Sometimes it will look like this:

array(3) {
  [0]=>
  string(1) "3"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "1"
}

 

Sometimes it will look like this:

array(3) {
  [0]=>
  string(1) "2"
  [1]=>
  string(1) "1"
}

 

Sometimes like this:

array(3) {
  [0]=>
  string(1) "5"
  [1]=>
  string(1) "4"
  [2]=>
  string(1) "3"
  [3]=>
  string(1) "2"
  [4]=>
  string(1) "1"
}

 

and so on.

 

It changes depending on who is logged on the website.

 

Is there anyway to cycle through it first to see what's there?

Link to comment
https://forums.phpfreaks.com/topic/226715-help-with-array/#findComment-1169994
Share on other sites

Could try something like:

 

<?php
$array = array(3,2,1); //array holding your db values.

$variables = array(100,50,5); //array holding your var values, this array should be set up so the key is the expected value of your DB array.

foreach($array as $k => $v) {
if(array_key_exists($k,$variables)) {
   $var[] = $variables[$k];
}
}

//This is all just echoing back to the screen.
echo '<pre>';
var_dump($array);
var_dump($variables);
var_dump($var);


$array = $var; //re-assign array to var.

echo 'Your array now holds:';

var_dump($array);
echo '</pre>';
?>

Link to comment
https://forums.phpfreaks.com/topic/226715-help-with-array/#findComment-1170000
Share on other sites

Hey jcbones, I tried your code and got the following. The last 3 arrays are the same. Is this what you were after?

 

array(3) {
  [0]=>
  string(1) "3"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "1"
}
array(3) {
  [0]=>
  int(100)
  [1]=>
  int(50)
  [2]=>
  int(5)
}
array(3) {
  [0]=>
  int(100)
  [1]=>
  int(50)
  [2]=>
  int(5)
}
Your array now holds:
array(3) {
  [0]=>
  int(100)
  [1]=>
  int(50)
  [2]=>
  int(5)
}

Link to comment
https://forums.phpfreaks.com/topic/226715-help-with-array/#findComment-1170034
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.