Can not do the array equation in php - 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

Related

How to echo array values which are incremented PHP

I have an array like this:
$aArray = array('one' => 0, 'two' => 0, 'three' =>0);
And a while loop like this:
$x = 50;
$y = 400;
$current = current($aArray);
while ($x<$y) {
$current++;
$x+=50;
if($x==$y) {
$current = next($aArray);
}
}
Now what I want is to show the array with the total times incrementation, but I don't know how. And is it able to show it without using a loop?
You can extract the keys of the array and then run according to index.
Consider the following modification:
$aArray = array('one' => 0, 'two' => 0, 'three' =>0);
$keys = array_keys($aArray);
$x = 50;
$y = 400;
$i = 0;
while ($x<$y) {
$aArray[$keys[$i]]++;
$x+=50;
if($x==$y) {
$i++;
}
}
print_r($aArray); // array('one' => 7, 'two' => 0, 'three' =>0);
If you don't want to loop you can just do:
$delta = $y - $x;
$cnt = intval($delta / 50);
if ($delta % 50 != 0)
$cnt++
Now $cnt will be 7 and you can set it in: $aArray["one"] = $cnt;
If you want the count the number of array incremented I have added a some line of coding
$x = 50;
$y = 400;
$aArray = array('one' => 0, 'two' => 0, 'three' =>0);
$countInc=0;
$current = current($aArray);
while ($x<$y) {
$current++;
$x+=50;
$countInc++;
if($x==$y) {
$current = next($aArray);
}
}
echo "Total Number of Increment from that Array: ". $countInc;

Get the combination from other array

I have two array
First
array(
0 => 100000,
1 => 50000,
2 => 100000,
3 => 100000);
Second
array(
0 => 150000,
1 => 200000,);
The problem is I want to get the combination from first array that formed each second array.
Example
Second array index 0 can be formed from first array index 0 and 1 and second array index 1 can be formed from first array index 2 and 3
I want to achieve like this
[0 => [0,1] , 1 => [2,3]]
Thanks for the help.
A simple an fast gready approach would be to first sort the arrays descending. After that, loop over the second one and collect from the first one as much values, till you reach your desired value.
$first = [
0 => 100000,
1 => 50000,
2 => 100000,
3 => 100000
];
$second = [
0 => 150000,
1 => 200000
];
arsort($first);
arsort($second);
$combinations = [];
foreach ($second as $search) {
$combination = [];
$sum = 0;
foreach ($first as $key => $val) {
if ($sum + $val > $search) continue;
$sum += $val;
$combination[] = $key;
if ($sum == $search) break;
}
if ($sum != $search) die("nothing found this way..");
foreach ($combination as $val) unset($first[$val]);
$combinations[] = $combination;
}
print_r($combinations);
Here is the simple idea to achieve your requirement. There would be many if's and but you need to consider yourself
<?php
$arr1 = [0 => 100000,1 => 50000,2 => 100000,3 => 100000];
$arr2 = [0 => 150000,1 => 200000];
//$arr2 = [0 => 250000,1 => 100000];
$count = 0;
$new = array();
for($i=0;$i<count($arr1);$i++){
if($arr1[$i] == $arr2[$count]){
$new[$arr2[$count]] = $arr1[$i];
$count++;
}else{
$sum = [$arr1[$i]];
for($j=$i+1;$j<count($arr1);$j++){
$sum[] = $arr1[$j];
if( array_sum($sum) == $arr2[$count]){
$new[$arr2[$count]] = $sum;
$count++;
}
}
}
}
print_r($new);
?>
Output1
Output2
Try with following code:
$arr = array(
0 => 100000,
1 => 50000,
2 => 100000,
3 => 100000);
$count = $val = 0;
$newArr = [];
foreach($arr as $a){
$val += $a;
$count++;
if($count == 2){
$newArr[] = $val;
$val = $count = 0;
}
}
print_r($newArr); die;

PHP - get array value if next element is not series

Here is my array
$array = array( 0 => 10, 1 => 9, 2 => 8, 3 => 6, 4=> 4 );
I want to get array value 6. because, 7 is missing before this value/series is break.
Please help me how can I do it easy & fast method.
The sequence could be calculated by subtracting the first value from the second value. Then you could for example use a for loop to loop through the values of the array and check if there is also a next value available by checking if there is an index + 1.
Then if that is the case you can subtract the current value in the loop from the next value and check if that result equals the step size.
If that is not the case, the next value of the iteration is the value that breaks the sequence and you can break out of the loop.
$array = [10,9,8,6,4];
if (count($array) > 2) {
$step = $array[0] - $array[1];
for ($i = 0; $i < count($array); $i++) {
if (isset($array[$i + 1]) && $array[$i] - $array[$i + 1] !== $step) {
$wrongValue = $array[$i + 1];
echo sprintf(" The step count is %d, but after %d comes %d which breaks the sequence.",
$step, $array[$i], $wrongValue
);
break;
}
}
}
Demo
<?php
$sequence =
[
0 => 10,
1 => 9,
3 => 8,
4 => 6,
5 => 4
];
$last = null;
foreach($sequence as $k => $v)
{
if(!is_null($last) && $last - $v > 1)
break;
$last = $v;
}
var_dump($k, $v);
Output:
int(4)
int(6)
Loop through it, save the previous values and compare with current one:
<?php
function findMissing($array) {
$missing = [];
foreach($array as $key => $val) {
if(isset($previousValue) && $previousValue-1!=$val) {
echo "not in series: ".($previousValue-1) .", returning ".$val."<br>\n";
$missing[] = $val;
}
$previousValue=$val;
}
return $missing;
}
// USAGE:
$array = array( 0 => 10, 1 => 9, 2 => 8, 3 => 6, 4=> 4 );
findMissing($array);
// not in series: 7, returning 6
// not in series: 5, returning 4
$array2 = array( 10, 9, 8, 6, 5 );
$missingValues = findMissing($array2);
// not in series: 7, returning 6
var_dump($missingValues);
// array(1) { [0]=> int(6) }
I'm not sure I understand what you want to achieve, but let's start it here.
UPDATED:
for($i = 0; $i < count($array); ++$i) {
if($i > 0) {
if($array[$i] != ($array[$i-1]-1)) {
echo($array[$i]);
break;
}
}
}
Output:
6

Counting occurrence of specific value in an Array with PHP [duplicate]

This question already has answers here:
Count number of values in array with a given value
(8 answers)
Closed 3 years ago.
I am trying to find a native PHP function that will allow me to count the number of occurrences of a particular value in an array. I am familiar with the array_count_values() function, but that returns the count of all values in an array. Is there a function that allows you to pass the value and just return the instance count for that particular value? For example:
$array = array(1, 2, 3, 3, 3, 4, 4, 5, 6, 6, 6, 6, 7);
$instances = some_native_function(6, $array); //$instances will be equal to 4
I know how to create my own function, but why re-invent the wheel?
function array_count_values_of($value, $array) {
$counts = array_count_values($array);
return $counts[$value];
}
Not native, but come on, it's simple enough. ;-)
Alternatively:
echo count(array_filter($array, function ($n) { return $n == 6; }));
Or:
echo array_reduce($array, function ($v, $n) { return $v + ($n == 6); }, 0);
Or:
echo count(array_keys($array, 6));
This solution may be near to your requirement
$array = array(1, 2, 3, 3, 3, 4, 4, 5, 6, 6, 6, 6, 7);
print_r(array_count_values($array));
Result:
Array
( [1] => 1 ,[2] => 1 , [3] => 3, [4] => 2,[5] =>1, [6] => 4, [7] => 1 )
for details.
As of PHP 5.4.0 you can use function array dereferencing for the index [6] of the array resulting from array_count_values():
$instances = array_count_values($array)[6];
So to check and assign 0 if not found:
$instances = array_count_values($array)[6] ?? 0;
Assume we have the following array:
$stockonhand = array( "large green", "small blue", "xlarge brown", "large green", "medieum yellow", "xlarge brown", "large green");
1) Copy and paste this function once on top your page.
function arraycount($array, $value){
$counter = 0;
foreach($array as $thisvalue) /*go through every value in the array*/
{
if($thisvalue === $value){ /*if this one value of the array is equal to the value we are checking*/
$counter++; /*increase the count by 1*/
}
}
return $counter;
}
2) All what you need to do next is to apply the function every time you want to count any particular value in any array. For example:
echo arraycount($stockonhand, "large green"); /*will return 3*/
echo arraycount($stockonhand, "xlarge brown"); /*will return 2*/
Say I have an array like this:
$array = array('', '', 'other', '', 'other');
$counter = 0;
foreach($array as $value)
{
if($value === '')
$counter++;
}
echo $counter;
This gives the number of times ' ' is repeating in the array
This is exactly what you looking for
<?php
$MainString = 'Yellow Green Orange Blue Yellow Black White Purple';
$FinderString = 'Yellow Blue White';
$mainArray = explode(" ", $MainString);
$findingArray = explode(" ", $FinderString);
$count = 0;
$eachtotal = array_count_values($mainArray);
foreach($findingArray as $find){
$count += $eachtotal[$find];
}
echo $count;
?>

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