The title isn't very descriptive and I apologize, but I couldn't think of a better way to explain it. I have up to 10 serialized arrays in a database. I pull them down and unserialize them into a new array as such:
$specimen0 = unserialize($row['specimen0']);
$specimen1 = unserialize($row['specimen1']);
This is then formatted into an ordered list showing the specimens. Since there is a ton of data for each specimen I don't want to code it over and over again 10 times. My while loop looks as such:
while($i <= $num) {
if(isset($specimen{$i})) {
echo 'Yep';
}
$i++
}
That is the generalized version. For some reason the i variable isn't appending itself to the specimen variable to create the one size fits all variable I want. This is probably something simple that I'm over looking or php won't handle it the way I need. Any help would be greatly appreciated.
while($i <= $num) {
$target='specimen'.$i;
if(isset($$target)) {
echo 'Yep';
}
$i++
}
look at variable variables
Fatherstorm described how to correct you code very well. what makes me wonder is this: why don't you use an array like this:
$specimen = array();
$specimen[0] = unserialize($row['specimen0']);
$specimen[1] = unserialize($row['specimen1']);
// maybe you could also use an foreach($specimen as $key=>$array) here,
// don't know what you're trying to do...
while($i <= $num) {
if(isset($specimen[$i])) {
echo 'Yep';
}
$i++
}
otherwise you would have to use variable variables like the others mentioned - and this will end up in unreadable (and unmaintainable) code. if you want to use something like an array, take an array for the job.
while($i <= $num) {
$var='specimen'.$i;
if(isset(${$var})) {
echo 'Yep';
}
$i++
}
what you tried to do:
$str='abcdef';
echo $str{4}; //echo e;
$i=3;
echo $str{$i};//echo d
Related
So, guys, my problem is that i'm creating an array from a mysql column, but, when i echo the array items, it returns me nothing, i'm about this for a while and i'm not seeing a possible error, hope can get some help. Here' s my code: (I know about the mysql to mysqli, but i'm just beginning and trying the logical stuff. :))
$duracao = mysql_query(
"SELECT SUM(fim_periodo-inicio_periodo)/0.01666667 AS mysum
FROM afunda_eleva_$a"
); //THIS $duracao IS INSIDE A FOR LOOP THAT EXECUTES THE QUERY IF A CONDITION IS SATISFIED (DEPENDING ON $a and $prevNum), it is working fine!
while ($row2 = mysql_fetch_assoc($duracao))
{
$duracao_afunda_eleva[] = $row2['mysum'];
}
so, to test some possible problems, i've put:
$i2 = sizeof($duracao_afunda_eleva);
echo $i2;
echo <br>;
which returns me the right size of the array, the problem comes here, i think:
for($i1 = 0 ; $i1 < sizeof($duracao_afunda_eleva); $i1++)
{
echo $duracao_afunda_eleva[$i1] or die("couldn't echo"
. mysql_error());
echo "<br>";
}
and this returns me no value. I really would appreciate any suggestion. Thanks in advance!
Try print_r instead of echo - echo outputs (string)$variable, which in case of an array is just "array". Also, echo is a language construct and not a function, so your or die(...) is problematic, as language constructs don't have return values.
Generally it's better to not use or die(...) constructs, and handle problems correctly (using a defined return value, so cleanup code can run, for example). Also, not being able to output anything with echo would mean that your php/whatever installation is seriously gone bad, at which point you probably won't even reach that line in your code, and even then it won't have anything to do with mysql.
Since the problem is not in the variable, try to use an alias in your MySQL select:
SELECT SUM(fim_periodo-inicio_periodo)/0.01666667 as mysum
Then in your PHP, you can get $row2['mysum'];
It may not solve the problem, but it is a good start.
Personally I use:
$arr = array ( /* ... */ );
echo "<pre>";
var_dump($arr);
echo "</pre>";
In your last for-loop, you use $i++, it should be $i1++
A quick tip is not to use the sizeof function in your for loop. This gets run with each iteration of your loop and you will notice an improvement in performance if you move it outside the loop (or use a foreach loop instead). e.g.
$count = sizeof($duracao_afunda_eleva);
for($i = 0 ; $i < $count; $i++) {
echo $duracao_afunda_eleva[$i] . '<br />';
}
or
// Foreach loop example
foreach ($duracao_afunda_eleva as $key => $value) {
echo $value . '<br />';
}
or what you could also do is this one line
echo implode('<br />', $duracao_afunda_eleva);
Use this code:
for($i1 = 0 ; $i1 < sizeof($duracao_afunda_eleva); $i1++)
{
echo $duracao_afunda_eleva[$i1] or die("couldn't echo". mysql_error());
echo "<br>";
}
You increased $i instead of $i1.
Although, with arrays, it's usually easier to use a foreach loop.
This runs from the first to the last element in the array.
Like so:
foreach ($duracao_afunda_eleva as $value) {
echo $value;
}
I would also suggest removing the space in $row2 ['mysum']:
$duracao_afunda_eleva[] = $row2['mysum'];
Edit
Just noticed it now, but your fetch-statement is wrong... It has a typo in it:
while ($row2 = mysql_fetch_assoc($duracao))
Make sure it reads mysql instead of myqsl.
I am theming a drupal content type, and I have a set of similarly named variables. e.g. field_anp_1, field_anp_2,..., field_anp_10. I want to dynamically print them out from within a for loop. Normally, one would print the values out individually by doing something like:
print $field_anp_1[0]['value'];
in my case, I can't do this because the last number changes. So, within a for loop, how would one print out these fields? I tried variable variables, but I don't seem to understand exactly what is going on there - and I don't think it likes the fact that this in an array. Any help would be greatly appreciated!
Definitely not an array. But you can use a variable as the name of a variable with {..}
ghoti#pc:~ $ cat invar.php
#!/usr/local/bin/php
<?php
$field_anp_3="three";
$field_anp_2="two";
for ($i=1; $i<5; $i++) {
$thisvar="field_anp_" . $i;
if (isset(${$thisvar})) {
printf("%s: %s\n", $i, ${$thisvar});
} else {
printf("%s: not set\n", $i);
}
}
ghoti#pc:~ $ ./invar.php
1: not set
2: two
3: three
4: not set
Alternately, if you are sure that the variables that do exist will be sequential. you can stop on failure (per comments below):
#!/usr/local/bin/php
<?php
$field_anp_1="one";
$field_anp_2="two";
$field_anp_3="three";
for ($i=1; $i<5; $i++) {
$thisvar="field_anp_" . $i;
if (!isset(${$thisvar})) {
break;
}
printf("%s: %s\n", $i, ${$thisvar});
}
I can see no reason for having an untold number of variables generated like that. But this is how you could collect them:
$vars = array();
foreach(get_defined_vars() as $name => $value) {
if(strpos($name, 'field_anp_') === 0) {
$vars[$name] = $value;
}
}
Now you would have your values as an associative array in $vars. Instead of adding the values to $vars, you could print them directly.
Update In response to your comment
$array = array('foo' => 'bar');
$x = 'foo';
$field_anp_bar = 'baz';
echo ${'field_anp_' . $array[$x]};
Ok, I figured it out. I simply needed to be more specific with PHP. To call a variable such as: $field_anp_0[0]['value'] from within a for loop, where 0 is increasing, one simply needs to do the following:
<?php
$numbers = array(123,235,12332,2342);
for($i; $i<count($numbers); $i++){
$var = "field_anp_".$numbers[$i];
printf("%s\n", ${$var}[0]['value']);
}
?>
This will allow me to list the fields that I will need to have printed out in the order I need to have them printed out. Then, I can use a for loop to print out a themed table for instance.
Thank you for the help!
Let me know if you want more details but:
I have an different number of inserts I need to make based on a POST form data that I created in a loop.
If I were to write it all out it would look like this:
$Scout1=$_POST['ScoutID1'];
$Scout2=$_POST['ScoutID2'];
and it keeps going until it reaches "x" I do have that number stored as
$ScoutCount
(so if the above code would post all the variables I brought over {$ScoutCount=2}
I can't find a way to do:
while (X>0){
$ScoutX=$_POST['ScoutIDX'];
X--;
}
how can I do this?
You might be looking for variable variables
But rather, I would recommend storing the data in an array, as opposed to individual variables. Then in a for loop, it could look like:
$scouts = array();
for ($i = 0; $i < 10; $i++)
{
$scouts[$i] = $_POST['ScoutID' . $i];
}
or something.
instead of having form fields called ScoutID1, ScoutID2 wtc name them
name="ScoutID[]"
then you will have a nice array with work with
//put scoutIDs into Array
$scouts = array();
for ($i = 1; $i <= $ScoutCount; $i++)
{
$scouts[$i] = $_POST['ScoutID' . $i];
}
Thanks - that may have seemed easy but I wasted a day trying to figure it out. thanks from the newbie to Php....
I have a large array.
In this array I have got (among many other things) a list of products:
$data['product_name_0'] = '';
$data['product_desc_0'] = '';
$data['product_name_1'] = '';
$data['product_desc_1'] = '';
This array is provided by a third party (so I have no control over this).
It is not known how many products there will be in the array.
What would be a clean way to loop though all the products?
I don't want to use a foreach loop since it will also go through all the other items in the (large) array.
I cannot use a for loop cause I don't know (yet) how many products the array contains.
I can do a while loop:
$i = 0;
while(true) { // doing this feels wrong, although it WILL end at some time (if there are no other products)
if (!array_key_exists('product_name_'.$i, $data)) {
break;
}
// do stuff with the current product
$i++;
}
Is there a cleaner way of doing the above?
Doing a while(true) looks stupid to me or is there nothing wrong with this approach.
Or perhaps there is another approach?
Your method works, as long as the numeric portions are guaranteed to be sequential. If there's gaps, it'll miss anything that comes after the first gap.
You could use something like:
$names = preg_grep('/^product_name_\d+$/', array_keys($data));
which'll return all of the 'name' keys from your array. You'd extract the digit portion from the key name, and then can use that to refer to the 'desc' section as well.
foreach($names as $name_field) {
$id = substr($names, 12);
$name_val = $data["product_name_{$id}"];
$desc_val = $data["product_desc_{$id}"];
}
How about this
$i = 0;
while(array_key_exists('product_name_'.$i, $data)) {
// loop body
$i++;
}
I think you're close. Just put the test in the while condition.
$i = 0;
while(array_key_exists('product_name_'.$i, $data)) {
// do stuff with the current product
$i++;
}
You might also consider:
$i = 0;
while(isset($data['product_name_'.$i])) {
// do stuff with the current product
$i++;
}
isset is slightly faster than array_key_exists but does behave a little different, so may or may not work for you:
What's quicker and better to determine if an array key exists in PHP?
Difference between isset and array_key_exists
I know I'm doing this a bad way... but I'm having trouble seeing any alternatives. I have an array of products that I need to select 4 of randomly. $rawUpsellList is an array of all of the possible upsells based off of the items in their cart. Each value is a product object. I know this is horribly ugly code but I don't see an alternative now.... someone please put me out of my misery so this code doesn't make it to production.....
$rawUpsellList = array();
foreach ($tru->global->cart->getItemList() as $item) {
$product = $item->getProduct();
$rawUpsellList = array_merge($rawUpsellList, $product->getUpsellList());
}
$upsellCount = count($rawUpsellList);
$showItems = 4;
if ($upsellCount < $showItems) {
$showItems = $upsellCount;
}
$maxLoop = 20;
$upsellList = array();
for ($x = 0; $x <= $showItems; $x++) {
$key = rand(0, $upsellCount);
if (!array_key_exists($key, $upsellList) && is_object($rawUpsellList[$key])) {
$upsellList[$key] = $rawUpsellList[$key];
$x++;
}
if ($x == $maxLoop) {
break;
}
}
Posting this code was highly embarassing...
Actually, pulling randomly from an array is a tough nut to crack - even Microsoft had trouble recently. That's a decent code sample for someone who I assume isn't an expert in algorithms, but also may be statistically skewed. As I said, it's difficult to do this right.
Thankfully, PHP already has the function array_rand, which seems to do what you want: return N items randomly chosen from an array. Is that what you're looking for?
$upsellList = array_rand($rawUpsellList, 4);
I am not really into PHP, but as an algorithm I will consider this pseudocode or whatever:
List<WhateverTypeYouWant> array;
List<WhateverTypeYouWant> selectedElements;
for (int i = 1; i <= 4; i++)
{
int randomIndex = random(array.size());
selectedElements.add(array[randomIndex]);
array.remove(randomIndex);
}
array_rand will let you pick one or more elements randomly from an array.
To use it (and save yourself a lot of headache), simply do something like
$upsellList = array_rand($rawUpsellList, 4);