How to count order number of values in an array? - php

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>');
}

Related

PHP - foreach increment more than 1

I have foreach loop in which I need to assign coordinates after certain steps. For this example $n+4 (174,178,182,...).
I know that solve multiple entering n++.
$n = 174;
foreach($items as $item){
echo $item . ' coor: ' . $n . '<br>';
$n++;
$n++;
$n++;
$n++;
}
I wonder if it can not be solved more elegantly.
You can use:
$n += 4;
When you put an operator before =, it creates an operator that combines the original value of the target with the source using that operation, so that's equivalent to:
$n = $n + 4;
Similarly, if you write:
$n *= 10;
it's the same as
$n = $n * 10;
#Barmar 's solution and explanation is correct and solves your issue. But here is an alternative way you could write that code which you may find helpful:
$n = 174;
foreach($items as $i => $item){
echo $item . ' coor: ' . $n + $i*4 . '<br>';
}
Note this will only work if your array keys are numeric and incrementing. If they're not then you just need to change $items in the foreach to array_values($items).

How to add variables that are passed on through the URL to an array?

<?php
$i = $_GET['i'];
echo $i;
$values = array();
while ($i > 0)
{
$expense = $_GET['expense_' + i];
$amount = $_GET['amount_' + i];
$values[$expense] = $amount;
i--;
print_r($values);
}
?>
i represents the number of sets of variables I have that have been passed through from the previous page. What I'm trying to do is add the expenses to the amounts and put them in an array as (lets just say for this example there were 3 expenses and 3 amounts) [expense_3 => amount_3, expense_2 => amount_2, expense_1 => amount_1]. The names of the variables are successfully passed through via the url as amount_1=50, amount_2=50, expense_1=food, expense2=gas, etc... as well as $i, I just dont know how to add those variables to an array each time.
Right now with this code I'm getting
4
Array ( [] => ) Array ( [] => ) Array ( [] => ) Array ( [] => )
I apologize if I'm not being clear enough, but I am pretty inexperienced with PHP.
The syntax error you're getting is because you're using i instead of $i - however - that can be resolved easily.
What you're looking to do is "simple" and can be accomplished with string-concatenation. It looks like you're attempting this with $_GET['expense'] + i, but not quite correct.
To properly build the parameter name, you'll want something like $_GET['expense_' . $i], here you can see to concatenate strings you use the . operator - not the + one.
I'm going to switch your logic to use a for loop instead of a while loop for my example:
$values = array();
for ($i = $_GET['i']; $i > 0; $i--) {
$expense = $_GET['expense_' . $i];
$amount = $_GET['amount_' . $i];
$values[$expense] = $amount;
}
print_r($values);
This is following your original logic, but it will effectively reverse the variables (counting from $i down to 1). If you want to count up, you can change your for loop to:
$numVariables = $_GET['i'];
for ($index = 1; $index <= $numVariables; $index++) {
$expense = $_GET['expense_' . $index];
...
Or just serialize the array and pass it to the next site, where you unserialize the array
would be much easier ;)

PHP remove undefined offset:

I would like to ask what is this kind of error undefined offset:4
my code is
$url = 'http://gogo.com, http://yoyo.com, http://gogo.com, http://yoyo.com, http://gogo.com, http://yoyo.com';
$key = 'key1, key2, key3';
$xurl = explode( "\n", $url );
$xkey = explode( "\n", $key );
$count = count( $xkey );
echo $count;
$i = 0;
while ( $i <= $count ) {
if(empty($xkey[$i])){
unset($xkey[$i]);
}
echo $xkey[$i];
$i++;
}
the echo is key1 key2 key3
but the thing is that i need to loop the xkey equal to my url
so the echo should be but i only have 3keyword i mean the keyword is less than the url.
how can i make it something like this below...
http://gogo.com - key1
http://yoyo.com - key2
http://gogo.com - key3
http://yoyo.com - key1
http://gogo.com - key2
http://yoyo.com - key3
What it means is that the script is looking for the value of $xkey[4], but that element doesn't exist. This is happening because array keys like this are 0-based, so the fourth element will be $xkey[3]. Change your while statement to while ( $i < $count ) as count will be 4, but the max key will be 3.
You're doing
while ( $i <= $count ) {
where $count is the number of element in $xkey (let say 4 elements)
As arrays are 0 indexed, the element $xkey[3] is the 4th and last element.
$xkey[4] will bring you that error.
Now, delete "=" in this while ( $i <= $count ) { and it should disappear.
I'm not sure where to start explaining what your problem is, you have an entirely wrong approach. To get the result you want you need to do this:
$urlString = 'http://gogo.com, http://yoyo.com, http://gogo.com, http://yoyo.com, http://gogo.com, http://yoyo.com';
$keyString = 'key1, key2, key3';
$urls = explode(',', $urlString);
$keys = explode(',', $keyString);
$i = 0;
$count = count($keys);
foreach ($urls as $url) {
echo $url, ' - ', $keys[$i % $count], PHP_EOL;
$i++;
}

PHP Count values of an array

Is there a way to count the values of a multidimensional array()?
$families = array
(
"Test"=>array
(
"test1",
"test2",
"test3"
)
);
So for instance, I'd want to count the 3 values within the array "Test"... ('test1', 'test2', 'test3')?
$families = array
(
"Test"=>array
(
"test1",
"test2",
"test3"
)
);
echo count($families["Test"]);
I think I've just come up with a rather different way of counting the elements of an (unlimited) MD array.
<?php
$array = array("ab", "cd", array("ef", "gh", array("ij")), "kl");
$i = 0;
array_walk_recursive($array, function() { global $i; return ++$i; });
echo $i;
?>
Perhaps not the most economical way of doing the count, but it seems to work! You could, inside the anonymous function, only add the element to the counted total if it had a non empty value, for example, if you wanted to extend the functionality. An example of something similar could be seen here:
<?php
$array = array("ab", "cd", array("ef", "gh", array("ij")), "kl");
$i = 0;
array_walk_recursive($array, function($value, $key) { global $i; if ($value == 'gh') ++$i; });
echo $i;
?>
The count method must get you there. Depending on what your actual problem is you maybe need to write some (recursive) loop to sum all items.
A static array:
echo 'Test has ' . count($families['test']) . ' family members';
If you don't know how long your array is going to be:
foreach($families as $familyName => $familyMembers)
{
echo $familyName . ' has got ' . count($familyMembers) . ' family members.';
}
function countArrayValues($ar, $count_arrays = false) {
$cnt = 0;
foreach ($ar as $key => $val) {
if (is_array($ar[$key])) {
if ($count_arrays)
$cnt++;
$cnt += countArrayValues($ar);
}
else
$cnt++;
}
return $cnt;
}
this is custom function written by me, just pass an array and you will get full count of values. This method wont count elements which are arrays if you pass second parameter as false, or you don't pass anything. Pass tru if you want to count them also.
$count = countArrayValues($your_array);

Possible to access PHP parse_str array values by index?

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];
}

Categories