Possible to access PHP parse_str array values by index? - php

Hopefully this is a simple answer or doable in some other way. I want to use parse_str to store my querystring values in an array.
$querystring = "value1=SKIP&value2=SKIP&value3=GET&value4=GET";
parse_str($querystring, $fields);
Accessing the data by name works correctly:
echo $fields['value3'];
... but accessing via index does not:
echo $fields[2];
The reason I want to access by index instead of name is because after the 2nd array value, the rest of the querystring parameters will be DYNAMICALLY generated. In other words, for the processing I'm doing -- I want to get all parameters AFTER the 2nd one. To do that, I was going to use a simple FOR loop starting from the 3rd value in the array to the sizeof(myArray);.
Any ideas how I can accomplish this?

You have to generate an indexed array then. You could for example use:
$indexed = array_values($fields);
print $indexed[2]; // eqivalent to $fields["value3"];
Note that the index starts from 0.
If you want you could also combine the named array with the indexed version:
$fields = array_merge($fields, array_values($fields));
$fields[2] == $fields["value3"];

$i = 0;
foreach ($fields as $key => $value) {
$fields[$i] = $value; //or just put your code here, and use $i
$i++;
}
for ($j = 2; $j < $i; $j++) {
//do something with $fields[$j]
}

Here:
$querystring = "value1=SKIP&value2=SKIP&value3=GET&value4=GET";
parse_str($querystring, $fields);
$arr = array_slice($fields, 2, count($fields), true);
foreach($arr as $key=>$value) {
echo $key . "=>" . $value;
}

Just concatenate a string with an integer:
echo $fields["value" . $myInteger + 1];
where myInteger is your value (for loop, etc.). You need to add 1 because your strings are one-based.
Example:
for ($i = 2; $i < sizeof($myArray); $i++)
{
echo $fields["value" . $i + 1];
}

Related

Print all values of array with a nested index in PHP without a loop

I have an array which has nested String that I want to output without a loop.
Here is the array:
$field_my_array[0]['string_term']->name = "First";
$field_my_array[1]['string_term']->name = "Second";
$field_my_array[2]['string_term']->name = "Third";
$field_my_array[3]['string_term']->name = "Forth";
$field_my_array[4]['string_term']->name = "Fifth";
I want to output this as
First, Second, Third, Forth, Fifth
This is what I tried (but it's in loop)
for ($ctr = 0; $ctr < count($field_my_array); $ctr ++) {
print $field_my_array[$ctr]['string_term']->name;
if ($ctr < count($field_my_array) -1) {print ", ";}
}
I'd be inclined to break this down into two parts:
Convert the array into a simplified version that just contains the values you want to concatenate. For that, you can use array_map() (https://www.php.net/manual/en/function.array-map.php).
Join the elements of the array without an extra comma on the end. The perfect use case for implode() (https://www.php.net/manual/en/function.implode.php).
Example:
echo implode(', ', array_map(function($item) {
return $item['string_term']->name;
}, $field_my_array));
I am not sure what you're trying to achieve. If you don't want to loop, then you have to manually write like this:
echo $field_my_array[0]['string_term']->name;
echo ", ";
echo $field_my_array[1]['string_term']->name;
...
and so on. Looping is a fundamental programming construct that allows us to automate with a simple count.
for ($ctr = 0; $ctr < count($field_my_array); $ctr ++) {
print $field_my_array[$ctr]['string_term']->name;
if ($ctr < count($field_my_array) -1) {print ", ";}
}
A better one would be this:
$field_my_array[0]['string_term']->name = "First";
$field_my_array[1]['string_term']->name = "Second";
$field_my_array[2]['string_term']->name = "Third";
$field_my_array[3]['string_term']->name = "Forth";
$field_my_array[4]['string_term']->name = "Fifth";
$names = array();
for ($ctr = 0; $ctr < count($field_my_array); $ctr ++) {
$names[] = $field_my_array[$ctr]['string_term']->name;
}
// this creates a string with a comma between items from array
$full_text = implode(', ',$names);
echo $full_text ;
You can use array_merge_recursive with implode
$c = array_merge_recursive(...$field_my_array);
echo implode(',', $c['string_term']['name']);
Live DEMO https://3v4l.org/GdhM5

Iterate on PHP variable (list/array) then output the index based on its value

Using the following example in PHP:
$priv['PAGE_A'] = 11;
$priv['PAGE_B'] = 22;
$priv['PAGE_C'] = 33;
$priv['PAGE_D'] = 44;
1) I would like to iterate on the 4 values in $priv. Would 'foreach' be the correct way to do it?
2) If the value is higher than a given number, I would like to echo the index of this value. Not sure how to do it. The comparaison must be INT (not string).
Ex. using "30" it would output:
PAGE_C
PAGE_D
Is it possible? Or maybe I am not using the correct container for what I'm trying to do ?
PS. How would you call the type of "$priv" in this example ? An array ? An indexed variable ? A dictionary ? A list ?
Thank you.
basically:
<?php
function foo($var){
$priv['PAGE_A'] = 11;
$priv['PAGE_B'] = 22;
$priv['PAGE_C'] = 33;
$priv['PAGE_D'] = 44;
$out='';
foreach ($priv as $k=>$v){
if ($v >$var){
$out .= $k.'<br>';
}
}
return $out;
}
echo foo('30');
demo: http://codepad.viper-7.com/GNX7Gf
Just create an array with the letters to iterate over.
$letters = array('A','B','C','D');
for($i=0;$i<count($letters);$i++) {
if($priv['PAGE_' . $letters[$i]] > /*value*/) {
echo $priv['PAGE_' . $letters[$i]];
}
}
$priv is an array.
Also, it's not too clear to me what you are exactly trying to do. Are you trying to echo the value of the array element if it's greater than a constant value?
We could do it using PHP builtin array functions. Its good to use builtin functions if possible in case of performance.
array_walk will do the trick for you. In this case $priv is an associative PHP array. Following is the one line script that will do what you want to achieve:
$input = 30;
$priv['PAGE_A'] = 11;
$priv['PAGE_B'] = 22;
$priv['PAGE_C'] = 33;
$priv['PAGE_D'] = 44;
array_walk($priv, function($value, $key, $input){ if($value > $input) echo $key . '<br>';}, $input);

How can I target a specific variable by name using a for loop?

Is it possible to use a for loop where $i is part of the variable name? I'm trying to get this for loop to list the fruits:
$item1name = "apple";
$item2name = "orange";
$item3name = "banana";
for($i=0, $i<2, $i++) {
echo = "<li>$item?????</li>";
}
// should result in:
// <li>apple</li><li>orange</li><li>banana</li>
I realize I can put the fruits in an $itemname array and easily echo $itemname[$i], but that isn't what I'm asking. Is it possible to do this when $i is part of the variable name?
It is possible with the use of variable variables:
for($i=1; $i<=3; $i++) {
echo "<li>" . ${'item'.$i.'name'} . "</li>";
}
Note that your original code wasn't syntactically correct. I've fixed it. Also note how $i value changed. Your variable numbers are from 1 to 3, not 0 to 1.
But I don't see why you'd want this. Simply use an array instead.
Demo

putting a foreach inside foreach

I'm trying to loop some array using foreach.
This is the code which demonstrates what I'm doing:
$arr1=array("32,45,67,89");
$arr2=array("5,3,2,1");
foreach($arr1 as $key => $val){
foreach($arr2 as $key2 =>$val2){
echo $val."-".$key2."-".$val2;
}
}
However, this outputs
32-0-5
32-1-3
32-2-2
32-3-1
and I want to display it like this instead
32-1-5
45-2-3
67-3-2
89-3-1
How can I solve this? Since I'm a beginner I don't know what to do.
You don't want to loop over the 2nd array, you just want to get the value at a certain position. Try it like this:
foreach($arr1 as $key => $val){
$val2 = $arr2[$key];
echo $val."-".($key+1)."-".$val2;
}
I assume you're doing a double foreach because you actually want to print 4*4 = 16 rows. I also assume that you mistyped the last row, where you have a 3 instead of a 4.
Just using ($key2+1) can be enough for you ?
$arr1=array("32,45,67,89");
$arr2=array("5,3,2,1");
foreach($arr1 as $key => $val){
foreach($arr2 as $key2 =>$val2){
echo $val."-" . ($key2+1) . "-".$val2;
}
}
Do not nest the loops;
Use one loop and print array1[i]."-".array2[i]
You can use for loop instead of foreach too:
$arr1=array(32,45,67,89);
$arr2=array(5,3,2,1);
for ($i = 0; $i < 4; $i++) {
echo $arr1[$i] . "-" . ($i+1) . "-" . $arr2[$i];
}
$i<count ($arr1) counts the number of elements in the array.
And then stop once it gets to the end.
If you have the name number of elements in each array. This would be great for you or even to create tables dynamically.
$arr1=array("32,45,67,89");
$arr2=array("5,3,2,1");
for ($i=0; $i<count ($arr1) ; $i++){
echo $arr1[$i] . "-" . $arr1[$i]."-". $arr2[$i] ;
}

How to count order number of values in an array?

I have an array with a few values and want to do something like this:
$arrayvalues = array_reverse(explode(', ', somefunction()));
foreach ( $arrayvalues as $arrayvalue ) :
printf('<li class="'.$countvalue.'">'.$arrayvalue.'</li>');
endforeach;
I want to have in $countvalue the number of the value in the array
ie... the array will be something like this: ("apple", "orange", "grapefruit")
I want the number to match the order number of these values
apple = 1, orange = 2, grapefruit = 3
or actually even if it's just an incremental number according to the values echoed it doesn't matter, I just need to insert a css class represented by an incremembtal number
I tried playing $i... count... but I don't know how to achieve what I want; I'm more a designer than a coder, I looked in the PHP help but couldn't find a clear solution for my case
thank you
You already have an incremental number based on order. Keep in mind, this only works if your key's are 0-based. If you use an associative array you will need to use a for loop instead (as suggested by nickb).
$arrayvalues = array_reverse(explode(', ', somefunction()));
foreach ( $arrayvalues as $key => $arrayvalue ){
echo "<li class='$key'>$arrayvalue</li>";
}
$arrayvalues = array_reverse(explode(', ', somefunction()));
$i = 0;
foreach ( $arrayvalues as $arrayvalue )
{
$i++;
printf('<li class="'.$i.'">'.$arrayvalue.'</li>');
}
Use a for loop to iterate over your array, like so:
for( $i = 0, $j = count( $arrayvalues); $i < $j; $i++) :
printf('<li class="' . ($i + 1) . '">' . $arrayvalues[$i] . '</li>');
endfor;
If you want the index $i to start at one, you need to add one in the printf statement.
Side note: You don't need printf here if you're not actually generating formatted output.
$arrayvalues = array_reverse(explode(', ', somefunction()));
$i=0;
foreach ( $arrayvalues as $arrayvalue ) :
++$i;
$countvalue = $i;
printf('<li class="'.$countvalue.'">'.$arrayvalue.'</li>');
endforeach;
We (or I) advise you use a normal for loop.
for($i = 0; $i < count($arrayvalues); $i++) {
printf('<li class="'.($i+1).'">'.$arrayvalue.'</li>');
}

Categories