sequence of real numbers in an array - php

I have several arrays as follows:
$number1 = array('A', 0.42);
$number2 = array('B', 0.44);
$number3 = array('C', 0.41);
$number4 = array('D', 0.43);
I want to display the results like this:
0.41
0.42
0.43
0.44
how to display the results like that? thanks :)

If you do:
echo $number3[1], "\n";
echo $number1[1], "\n";
echo $number4[1], "\n";
echo $number2[1], "\n";
You will get
0.41
0.42
0.43
0.44
But if you want to learn something about sorting you should read the manual.

The way you are using data and array is wrong. What if tomorrow you have 500 more numbers to sort ?
You should have one array that contain all your values.
<?
$data = array(
"A" => 0.45,
"B" => 0.43,
"C" => 0.41,
"D" => 0.42
);
asort($data);
foreach ($data as $key => $val) {
echo "$key = $val\n";
}
?>
should print something like
C = 0.41
D = 0.42
B = 0.43
A = 0.45

Personally I would condense that code into one array, which would allow a nice for / foreach loop, and sorting:
$numbers = array(
'A' => 0.42,
'B' => 0.44,
'C' => 0.41,
'D' => 0.43
);
asort($numbers);
foreach ($numbers as $number)
{
echo $number . '<br />';
}

You don't need to remake your arrays. You can use the double $$. This will print not the variable, but will try to access a variable that is stored in the value.
Like this:
$number1 = array('A', 0.42);
$number2 = array('B', 0.44);
$number3 = array('C', 0.41);
$number4 = array('D', 0.43);
$k = 1;
$name = 'number' . $k;
while ( isset($$name) )
{
$tmp = $$name;
echo $tmp[1] . '<br/>';
$k++;
$name = 'number' . $k;
}

Related

Can not do the array equation in php

I am trying to create an array equation where the array value will be equated to the existing sequence, but I can not display it in array..how do I fix it?
$ht = array('day' => 1,'day' =>2,'day' =>3,'day' =>4);
for ($x = 1; $x <= 10; $x++) {
if($x == $ht['day']){
echo 'x';
}else{
echo $x;
}
}
Which I expect xxxx5678910 but I result 123x45678910
This is your array :
$ht = array('day' => 1,'day' =>2,'day' =>3,'day' =>4);
I you just do var_dump($ht); you will see that you have :
array (size=1)
'day' => int 4
So try this to get what you want :
$ht = array(1 => 1, 2 => 2, 3 => 3, 4 => 4);
for ($x = 1; $x <= 10; $x++) {
if(!empty($ht[$x])){
echo 'x';
}else{
echo $x;
}
}
Output is : xxxx5678910
You have multiple way to achieve it, that's just one among other :)
When u use same key, u overwrite your array key, so at the and u have only one record in your array, u can try something like this:
<?php
$ht = array('day1' => 1,'day2' =>2,'day3' =>3,'day4' =>4);
var_dump($ht);
for ($x = 1; $x <= 10; $x++) {
if (isset($ht['day' . $x])) {
if($ht['day' . $x] == $x){
echo 'x';
}
} else{
echo $x;
}
}
?>
Return :
xxxx5678910
You don't need to loop at all to get the expected output.
You can use range() to create an array with numbers 1 to 10 as in the loop.
Then array_diff finds the numbers not in the $ht array so that they can be echoed with implode.
$ht = array(1 => 1, 2 => 2, 3 => 3, 4 => 4);
$range = range(1,10);
$diff = array_diff($range, $ht); // [5,6,7,8,9,10]
echo str_repeat("x", count($ht)) . implode("", $diff);
https://3v4l.org/ZCU15
If the numbers are not always consecutive you can use array_intersect, array_fill and array_flip to create the new array with "x" instead of numbers in $ht array.
Then use array_replace to replace number values with "x" and output with implode.
$ht = array(1 => 1, 2 => 2, 3 => 3, 4 => 9);
$range = range(0,10);
unset($range[0]); // unset 0 since you want 1 as lowest
$x = array_intersect_key(array_fill(1,max($ht), "x"), array_flip($ht));
// $x = [1=>"x", 2=>"x", 3 => "x", 9=>"x"]
$new = array_replace($range, $x);
echo implode("", $new);
https://3v4l.org/gtSl9

Is there an elegant way to start a foreach from the second index and then do the rest?

If I have the following:
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
foreach ($a as $v) {
echo $v;
}
How can I make it output:
2, 1, 3, 17
Quoting the PHP Manual on Language Operators:
The + operator returns the right-hand array appended to the left-hand
array; for keys that exist in both arrays, the elements from the
left-hand array will be used, and the matching elements from the
right-hand array will be ignored.
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
$b = array_values($a);
echo implode(', ', array($b[1], $b[0]) + $b), PHP_EOL;
Output:
2, 1, 3, 17
$values = array_values($a);
echo "{$values[1]}, {$values[0]}, "
foreach (array_slice($values, 2) as $v){
echo "$v, "
}
If you care about last comma...
$values = array_values($a);
echo "{$values[1]}, {$values[0]}, "
$lastIndex = count($values) - 1;
foreach (array_slice($values, 2) as $k => $v){
echo $v;
if ($k != $lastIndex){
echo ", ";
}
}
You could probably do something like:
<?php
$my_array = array(...);
$keys = array_keys($my_array);
$second_key = $keys[1]; // if your array can be whatever size, probably want to check that first
echo $my_array[$second_key];
foreach ($my_array as $key => $value) {
if ($key == $second_key) {
continue;
}
echo $value;
}
?>

PHP: How to print associative array using while loop?

I have a simple associative array.
<?php
$assocArray = array('a' => 1, 'b' => 2, 'c' => 3);
?>
Using only while loop, how can I print it in this result?
$a = 1
$b = 2
$c = 3
This is my current solution but I think that this is not the efficient/best way to do it?
<?php
$assocArray = array('a' => 1, 'b' => 2, 'c' => 3);
$keys = array_keys($assocArray);
rsort($keys);
while (!empty($keys)) {
$key = array_pop($keys);
echo $key . ' = ' . $assocArray[$key] . '<br />';
};
?>
Thanks.
try this syntax and this is best efficient way to do your job...........
while (list($key, $value) = each($array_expression)) {
statement
}
<?php
$data = array('a' => 1, 'b' => 2, 'c' => 3);
print_r($data);
while (list($key, $value) = each($data)) {
echo '$'.$key .'='.$value;
}
?>
For reference please check this link.........
Small Example link here...
The best and easiest way to loop through an array is using foreach
foreach ($assocArray as $key => $value)
echo $key . ' = ' . $value . '<br />';
Try this;
$assocarray = array('a' => 1, 'b' => 2, 'c' => 3);
$keys = array_keys($assocarray);
rsort($keys);
while (!empty($keys)) {
$key = array_pop($keys);
echo $key . ' = ' . $assocarray[$key] . '<br />';
};
I have a simple solution for this, it will get the job done..
$x = array(0=>10,1=>11,2=>"sadsd");
end($x);
$ekey = key($x);
reset($x );
while(true){
echo "<br/>".key($x)." = ".$x[key($x)];
if($ekey == key($x) )break;
next($x);
}
Try code below:
$assocArray = array('a' => 1, 'b' => 2, 'c' => 3);
$obj = new ArrayObject($assocArray);
foreach ( $obj as $key => $value ) {
echo '$' . $key .'='. $value . "<br/>";
}

Get the name of the variable which has the highest/biggest value with PHP

I have 4 variables and each of those have an integer assigned to them. Could anybody please let me know how I can get the name of the variable which has the highest value?
Thanks in advance.
Here is a solution to the question you asked:
$arr = compact('v1', 'v2', 'v3', 'v4');
arsort($arr);
$name = key($arr);
// get the value: ${$name}
However, having the variables stored in an array in the first place would make more sense. A better setup would be:
$arr = array('v1' => 543, 'v2' => 41, 'v3' => 1, 'v4' => 931);
arsort($arr);
$name = key($arr);
// get the value: $arr[$name]
Given four variables:
$a = 1;
$b = 3;
$c = 4;
$d = 2;
You can use compact to turn them into an associative array:
$array = compact('a', 'b', 'c', 'd');
var_dump($array); // array('a' => 1, 'b', => 3, 'c' => 4, 'd' => 2);
And then find the maximum key/value:
$max_key = $max_value = null;
foreach ($array as $key => $value) {
if (is_null($max_value) || $value > $max_value) {
$max_key = $key; $max_value = $value;
}
}

how to change the array key to start from 1 instead of 0

I have values in some array I want to re index the whole array such that the the first value key should be 1 instead of zero i.e.
By default in PHP the array key starts from 0. i.e. 0 => a, 1=> b, I want to reindex the whole array to start from key = 1 i.e 1=> a, 2=> b, ....
$alphabet = array("a", "b", "c");
array_unshift($alphabet, "phoney");
unset($alphabet[0]);
Edit: I decided to benchmark this solution vs. others posed in this topic. Here's the very simple code I used:
$start = microtime(1);
for ($a = 0; $a < 1000; ++$a) {
$alphabet = array("a", "b", "c");
array_unshift($alphabet, "phoney");
unset($alphabet[0]);
}
echo (microtime(1) - $start) . "\n";
$start = microtime(1);
for ($a = 0; $a < 1000; ++$a) {
$stack = array('a', 'b', 'c');
$i= 1;
$stack2 = array();
foreach($stack as $value){
$stack2[$i] = $value;
$i++;
}
$stack = $stack2;
}
echo (microtime(1) - $start) . "\n";
$start = microtime(1);
for ($a = 0; $a < 1000; ++$a) {
$array = array('a','b','c');
$array = array_combine(
array_map(function($a){
return $a + 1;
}, array_keys($array)),
array_values($array)
);
}
echo (microtime(1) - $start) . "\n";
And the output:
0.0018711090087891
0.0021598339080811
0.0075368881225586
Here is my suggestion:
<?php
$alphabet = array(1 => 'a', 'b', 'c', 'd');
echo '<pre>';
print_r($alphabet);
echo '</pre>';
?>
The above example will output:
Array
(
[1] => a
[2] => b
[3] => c
[4] => d
)
Simply try this
$array = array("a","b","c");
array_unshift($array,"");
unset($array[0]);
Ricardo Miguel's solution works best when you're defining your array and want the first key to be 1. But if your array is already defined or gets put together elsewhere (different function or a loop) you can alter it like this:
$array = array('a', 'b', 'c'); // defined elsewhere
$array = array_filter(array_merge(array(0), $array));
array_merge will put an array containing 1 empty element and the other array together, re-indexes it, array_filter will then remove the empty array elements ($array[0]), making it start at 1.
$array = array('a', 'b', 'c', 'd');
$array = array_combine(range(1, count($array)), array_values($array));
print_r($array);
the result:
Array
(
[1] => a
[2] => b
[3] => c
[4] => d
)
If you are using a range, try this code:
$data = array_slice(range(0,12), 1, null, true);
// Array ( [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 [8] => 8 [9] => 9 [10] => 10 [11] => 11 [12] => 12 )
I see this answer is very old, but my solution for this is by adding a +1 to your index. I'll do that because I think this is much faster and easy to read. When you print this it will start from 1 because 0+1 =1, then 2 etc.
foreach($items as $index => $item){
echo $index+1 . $item
}
I think it is simple as that:
$x = array("a","b","c");
$y =array_combine(range(1, count($x)), $x);
print_r($y);
$data = ['a', 'b', 'c', 'd'];
$data = array_merge([''], $data);
unset($data[0]);
I have found that this will perform slightly better, than the accepted solution, on versions of PHP 7.1+.
Benchmark code:
$start = microtime(1);
for ($a = 0; $a < 10000; ++$a) {
$data = ['a', 'b', 'c', 'd'];
$data = array_merge([''], $data);
unset($data[0]);
}
echo (microtime(1) - $start) . "\n";
$start = microtime(1);
for ($a = 0; $a < 10000; ++$a) {
$data = ['a', 'b', 'c', 'd'];
array_unshift($data, '');
unset($data[0]);
}
echo (microtime(1) - $start) . "\n";
Scripts execution time (PHP 7.4):
0.0011248588562012
0.0017051696777344
And the difference of these benchmarks will increase as the number of array values increases.
If you already have an array and want to reindex it
to start from index X instead of 0, 1, 3...N then:
// Check if an array is filled by doing this check.
if (count($your_array) > 0) {
// Let's say we want to start from index - 5.
$your_array = [5 => $your_array[0], ...array_slice($your_array, 1)];
}
About spread operator "..."
https://www.php.net/manual/en/migration56.new-features.php#migration56.new-features.splat
P.S.
Real-world scenario/use-case, what I've met in work doing a task for a client:
I had one <div> that contains two <tables>. Each <table> contains markup for the days of the week. The first one has days from Monday to Thursday. The second one has days from Friday to Sunday. So, in my task, I had the variable represent a week in which each day had hours of open and close. I needed appropriately divide that week's variable into two.
<table>
<?php for ($dayIndex = 0; $dayIndex < 4; $dayIndex++): ?>
<?php
$_timetable = array_slice($timetable, 0, 4);
// $renderTimetableRow is an anonymous function
// that contains a markup to be rendered, like
// a html-component.
$renderTimetableRow($_timetable, $dayIndex);
?>
<?php endfor; ?>
</table>
<table>
<?php for($dayIndex = 4; $dayIndex < 7; $dayIndex++): ?>
<?php
if (count($_timetable = array_slice($timetable, 4, 7)) > 0) {
$_timetable = [4 => $_timetable[0], ...array_slice($_timetable, 1)];
}
// $renderTimetableRow is an anonymous function
// that contains a markup to be rendered, like
// a html-component.
$renderTimetableRow($_timetable, $dayIndex);
?>
<?php endfor; ?>
</table>
try this
<?php
$stack = array('a', 'b', 'c', 'd');
$i= 1;
foreach($stack as $value){
$stack2[$i] = $value;
$i++;
}
$stack = stack2;
?>

Categories