Print array value and variable in order - php

I am sure there is a simpler solution to this that I am over looking
Here is some code that basically describes what I am doing:
$array = array('1.4','2.7','4.1','5.9');
$score = '4.4';
foreach($array as $value) {
if($score>$value){
$x = $value;
}
}
foreach($array as $value) {
if($x==$value){
echo $value."<br>";
echo $score."<-- <br>";
} else {
echo $value."<br>";
}
}
Will display as:
1.4
2.7
4.1
4.4<--
5.9
What I am trying to do is print the array values with the score value in order.

Why don't you change the array to actual numerical values and then sort it?
$array = array(1.4, 2.7, 4.1, 5.9);
$score = 4.4;
$array[] = $score;
sort($array);
Or if you need to work with strings:
$array = array('1.4', '2.7', '4.1', '5.9');
$score = '4.4';
$array[] = $score;
sort($array, SORT_NUMERIC);

For sorting, what might be the easiest is to use the sort() method (docs).
You're overwriting $x each time through your first loop. ... the way it's written, when you're done with the first loop, $x has the last value that's less than $score. (Are you identifying a cut-off line?)
After you've sorted with the sort() method, your second loop should work as you intend. There are tighter ways to do the printing (for example, you can implode()), but what you've got should work.

Related

PHP find double values in array and enumerate them

Hi I'm looking forward do find an easy solution to find and enumerate double values.
array("Papples", "Gelato", "Gelato", "Banana", "Papples","Papples")
to:
array("Papples", "Gelato", "Gelato2", "Banana", "Papples2","Papples3")
I could do it with a loop with if and write to second array procedure but isn't there a better solution for it?
Thank you!
you can try
<?php
$arr = array("Papples", "Gelato", "Gelato", "Banana", "Papples","Papples");
$countarray = array_count_values($arr);
$resultarray = array();
foreach ($countarray as $key=>$value) {
for ($i = 1; $i <= $value; $i++) {
$resultarray[]=$key.$i;
}
}
print_r($resultarray);
?>
Go with the loop and if, it's not difficult and will be pretty fast.
$delicatessen = [
"Papples", "Gelato", "Gelato", "Banana", "Papples","Papples"
];
foreach ($delicatessen as $e) {
if (#$counter[$e]++) $e .= $counter[$e];
$new[] = $e;
}
Basically what this does is to always add the element to the new array,
clearly, but modifying it or not. The condition is the $counter array
which will store the amount of times an item appears. All is created "on
the fly", PHP allows that.
When we retrieve $counter[$e] this element does not exist yet, so the
returned value makes the condition fail. However there is a side effect
that after the undef is returned, it will be increased (with ++) so
now $counter[$e] will be 1.
If on a future iteration this is accessed again the returned value of
1 will make the condition pass, with the side affect that at the point
the if statement is executed $counter[$e] will already be 2. The
statement concatenated this number to the end of the element.
This way, in the first time nothing is concatenated but there is the
side effect. On next iterations the number is concatenated to the
element.
The # operator is used here to suppress PHP notices. Since you're
dealing with undefined elements on first pass, you would get notices.
Script wouldn't break though. Of course this operator should be used
with caution, but in this case it just really helps simplifying code,
making it less strict.
$arr = array("Papples", "Gelato", "Gelato", "Banana", "Papples","Papples");
$arr_count = array_count_values($arr);
$new_arr = array();
foreach($arr_count as $key=>$val){
if($val > 1){
$k = 1;
for($i=0; $i<$val; $i++){
if($i==0){
$new_arr[] = $key;
}else{
$new_arr[] = $key.++$k;
}
}
}else{
$new_arr[] = $key;
}
}
echo "<pre>"; print_r($new_arr);
Test script: https://3v4l.org/iGf1s

Passing two variables into a 'foreach' loop

I need help regarding a foreach() loop. aCan I pass two variables into one foreach loop?
For example,
foreach($specs as $name, $material as $mat)
{
echo $name;
echo $mat;
}
Here, $specs and $material are nothing but an array in which I am storing some specification and material name and want to print them one by one. I am getting the following error after running:
Parse error: syntax error, unexpected ',', expecting ')' on foreach line.
In the Beginning, was the For Loop:
$n = sizeof($name);
for ($i=0; i < $n; $i++) {
echo $name[$i];
echo $mat[$i];
}
You can not have two arrays in a foreach loop like that, but you can use array_combine to combine an array and later just print it out:
$arraye = array_combine($name, $material);
foreach ($arraye as $k=> $a) {
echo $k. ' '. $a ;
}
Output:
first 112
second 332
But if any of the names don't have material then you must have an empty/null value in it, otherwise there is no way that you can sure which material belongs to which name. So I think you should have an array like:
$name = array('amy','john','morris','rahul');
$material = array('1w','4fr',null,'ff');
Now you can just
if (count($name) == count($material)) {
for ($i=0; $i < $count($name); $i++) {
echo $name[$i];
echo $material[$i];
}
Just FYI: If you want to have multiple arrays in foreach, you can use list:
foreach ($array as list($arr1, $arr2)) {...}
Though first you need to do this: $array = array($specs,$material)
<?php
$abc = array('first','second');
$add = array('112','332');
$array = array($abc,$add);
foreach ($array as list($arr1, $arr2)) {
echo $arr1;
echo $arr2;
}
The output will be:
first
second
112
332
And still I don't think it will serve your exact purpose, because it goes through the first array and then the second array.
You can use the MultipleIterator of SPL. It's a bit verbose for this simple use case, but works well with all edge cases:
$iterator = new MultipleIterator();
$iterator->attachIterator(new ArrayIterator($specs));
$iterator->attachIterator(new ArrayIterator($material));
foreach ($iterator as $current) {
$name = $current[0];
$mat = $current[1];
}
The default settings of the iterator are that it stops as soon as one of the arrays has no more elements and that you can access the current elements with a numeric key, in the order that the iterators have been attached ($current[0] and $current[1]).
Examples for the different settings can be found in the constructor documentation.
This is one of the ways to do this:
foreach ($specs as $k => $name) {
assert(isset($material[$k]));
$mat = $material[$k];
}
If you have ['foo', 'bar'] and [2 => 'mat1', 3 => 'mat2'] then this approach won't work but you can use array_values to discard keys first.
Another apprach would be (which is very close to what you wanted, in fact):
while ((list($name) = each($specs)) && (list($mat) = each($material))) {
}
This will terminate when one of them ends and will work if they are not indexed the same. However, if they are supposed to be indexed the same then perhaps the solution above is better. Hard to say in general.
Do it using a for loop...
Check it below:
<?php
$specs = array('a', 'b', 'c', 'd');
$material = array('x', 'y', 'z');
$count = count($specs) > count($material) ? count($specs) : count($material);
for ($i=0;$i<$count;$i++ )
{
if (isset($specs[$i]))
echo $specs[$i];
if (isset($material[$i]))
echo $material[$i];
}
?>
OUTPUT
axbyczd
Simply use a for loop. And inside that loop, extract values of your array:
For (I=0 to 100) {
Echo array1[i];
Echo array2[i]
}

Can use Array_sum or loop and make sum?

Have an array
array(array('a'=>'s','add'=>1),
array('a'=>'s1','add'=>2),
array('a'=>'s2','add'=>3)
...
...
);
I want to sum of all key add together.so result should be 6
Anyone know how to do this?
$sum = 0;
foreach($yourArray as $element) {
$sum += $element['add'];
}
echo $sum;
$sum = 0;
foreach($array1 as $array) {
$sum += $array['add'];
}
echo $sum; // will echo '6'
Unfortunately, array_sum only works on single-dimensional arrays. Since you're working with an array of associative arrays, you're going to have to approach it differently. If you know your array will have the same form as the one you've linked above, you can simply use something like this:
$total = 0;
foreach( $arrs as $arr )
{
$total += $arr['add'];
}
echo $total;
Where $arrs is the array you've defined above.
One liner echo array_sum(array_column($a, "add"));

Elegant Method of Inserting Code Between Loops

In web development, I often find I need to format and print various arrays of data, and separate these blocks of data in some manner. In other words, I need to be able to insert code between each loop, without said code being inserted before the first entry or after the last one. The most elegant way I've found to accomplish this is as follows:
function echoWithBreaks($array){
for($i=0; $i<count($array); $i++){
//Echo an item
if($i<count($array)-1){
//Echo "between code"
}
}
}
Unfortunately, there's no way that I can see to implement this solution with foreach instead of for. Does anyone know of a more elegant solution that will work with foreach?
I think you're looking for the implode function.
Then just echo the imploded string.
The only more elegant i can think of making that exact algorithm is this:
function implodeEcho($array, $joinValue)
{
foreach($array as $i => $val)
{
if ($i != 0) echo $joinValue;
echo $val;
}
}
This of course assumes $array only is indexed by integers and not by keys.
Unfortunately, I don't think there is any way to do that with foreach. This is a problem in many languages.
I typically solve this one of two ways:
The way you mention above, except with $i > 0 rather than $i < count($array) - 1.
Using join or implode.
A trick I use sometimes:
function echoWithBreaks($array){
$prefix = '';
foreach($array as $item){
echo $prefix;
//Echo item
$prefix = '<between code>';
}
}
If more elaborate code then an implode could handle I'd use a simple boolean:
$looped = false;
foreach($arr as $var){
if($looped){
//do between
}
$looped = true;
//do something with $var
}

How to get numeric key of new pushed item in PHP?

$arr[] = $new_item;
Is it possible to get the newly pushed item programmatically?
Note that it's not necessary count($arr)-1:
$arr[1]=2;
$arr[] = $new_item;
In the above case,it's 2
end() do the job , to return the value ,
if its help to you ,
you can use key() after to petch the key.
after i wrote the answer , i see function in this link :
http://www.php.net/manual/en/function.end.php
function endKey($array){
end($array);
return key($array);
}
max(array_keys($array)) should do the trick
The safest way of doing it is:
$newKey = array_push($array, $newItem) - 1;
You can try:
max(array_keys($array,$new_item))
array_keys($array,$new_item) will return all the keys associated with value $new_item, as an array.
Of all these keys we are interested in the one that got added last and will have the max value.
You could use a variable to keep track of the number of items in an array:
$i = 0;
$foo = array();
$foo[++$i] = "hello";
$foo[++$i] = "world";
echo "Elements in array: $i" . PHP_EOL;
echo var_dump($foo);
if it's newly created, you should probably keep a reference to the element. :)
You could use array_reverse, like this:
$arr[] = $new_item;
...
$temp = array_reverse($arr);
$new_item = $temp[0];
Or you could do this:
$arr[] = $new_item;
...
$new_item = array_pop($arr);
$arr[] = $new_item;
If you are using the array as a stack, which it seems like you are, you should avoid mixing in associative keys. This includes setting $arr[$n] where $n > count($arr). Stick to using array_* functions for manipulation, and if you must use indexes only do so if 0 < $n < count($arr). That way, indexes should stay ordered and sequential, and then you can rely on $arr[count($arr)-1] to be correct (if it's not, you have a logic error).

Categories