Getting the first occurrence of modulus eval - php

Consider this array:
$numbers = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
How can I loop through this array and get the FIRST number and the LAST number where the eval below is true?
foreach($numbers as $number){
if(($number % 2)==0){
//This will execute for the numbers 2,4,6, etc...
//The first occurrence here will be 2 and the last will be 16
}
}

If I got you right you want the min and the max only of even values.
Creating a helper variable should solve this easily.
<?php
$numbers = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
$even = array();
foreach($numbers as $number){
if(($number % 2) == 0){
//This will execute for the numbers 2,4,6, etc...
//The first occurrence here will be 2 and the last will be 16
// Store only even values on the array to access it later using min() and max() functions
$even[] = $number;
}
}
print_r($even);
echo min($even); // prints 2
echo max($even); // prints 16
?>

function getNumber(Array $numbers) {
foreach($numbers as $number) {
if (!($number % 2)) {
return $number;
}
}
}
$numbers = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
$first = getNumber($numbers); // 2
$last = getNumber(array_reverse($numbers)); // 16

$first = null;
$temp = null;
foreach($numbers as $number){
if(($number % 2)==0){
//This will execute for the numbers 2,4,6, etc...
//The first occurrence here will be 2 and the last will be 16
//
$temp = $number;
// Check if the first number has been assigned yet, if not set to $first
if ($first === null) {
$first = $number;
}
}
}
// Retrieve last valid value and set as last
$last = $temp;
Should do the trick

$numbers = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
foreach ($numbers as $number) {
if(0===($number%2))
{
(!isset($first)) ? $first=$number : $last=$number;
$last = $number;
}
}
echo $first.'<br />';
echo $last.'<br />';

Related

Return the number of all unique case-insensitive characters

I am trying create a function which returns the number of all unique case-insensitive
characters that occur >= $n times in a given string.
For example:
function getNumOfUniqueCharacters($str, $n) {
// ...
}
getNumOfUniqueCharacters('A1B2C3', 2); // 0
getNumOfUniqueCharacters('A1a1C1', 2);
// 2, because A and 1 both occur 2 or more times.
getNumOfUniqueCharacters('Alabama', 3); // 1
I did this:
function getNumOfUniqueCharacters($text)
{
$ret = 0;
$a = [];
$t = str_split(strtolower($text));
$l = count($t);
for ($i = 0; $i < $l; $i++) {
$c = $t[$i];
if (array_key_exists($c, $t)) {
if ($t[$c] === 1)
$ret += 1;
$t[$c] += 1;
} else {
$t[$c] = 1;
}
}
return $ret;
}
But it does not work so good, I need to add second argument $n.
How to add it correctly?
I hope I got your question right.
Here's my idea for this code:
<?php
$string = "A1B2C1A2b2b4b5";
function getNumOfUniqueCharacters($string, $n)
{
$occurrenceArray = array();
$text = str_split(strtolower($string));
//put each character in a keyValue array and count them
foreach($text as $character){
if(!array_key_exists($character, $occurrenceArray)) $occurrenceArray[$character] = 1;
else $occurrenceArray[$character]++;
}
//loop through keyValue array and remove everything that has value < $n
foreach($occurrenceArray as $key => $value)
{
if($value < $n) unset($occurrenceArray[$key]);
}
//return array
return $occurrenceArray;
}
print_r(getNumOfUniqueCharacters($string, 2));
This code right here will print the following:
Array (
[a] => 2
[1] => 2
[b] => 4
[2] => 3 )
Edit: If you need the count of how many characters repeat more than $n, you can simply replace the return with return count($occurrenceArray);
This task is pretty easy, if you use array functions of PHP:
function getNumOfUniqueCharacters(string $string = '', int $n = 1): int {
// Split the string by character and count the occurences of all values
$counted = array_count_values(mb_str_split(mb_strtolower($str)));
// Discard everything, that is does not match the $n parameter
$counted = array_filter($counted, function($a) use($n) {
return $a >= $n;
});
// Return the length of the remaining array
return count($counted);
}
Also note, that you may use mb_* functions, so your code will work with multibyte characters.
I have written you a function with a lot of comments to explain the thought process,
function getNumOfUniqueCharacters($string, $n = null) {
// Map all case-insensitive characters to an array
$map = str_split(strtolower($string), 1);
// Character registry
$reg = array_count_values($map);
// Filter out single occurances
$reg = array_filter($reg, function($v){return $v > 1;});
// Filter out less than $n occurances (if $n is not null)
if (null !== $n) {
$reg = array_filter($reg, function($v)use($n){return $v >= $n;});
}
// Return the number duplicate occurances (or more than n occurances)
return count($reg);
}
Usage:
echo getNumOfUniqueCharacters('A1B2C3', 2) . PHP_EOL;
echo getNumOfUniqueCharacters('A1a1C1', 2) . PHP_EOL;
echo getNumOfUniqueCharacters('Alabama', 3) . PHP_EOL;
echo getNumOfUniqueCharacters('Mississippi') . PHP_EOL;
Output:
0
2
1
3

Get a total from symmetric intigers from array in php?

ok so i have array for example $arr= "/43sdsd555ksldk66sd"544fdfd";
I take numbers using preg_match_all '/\d+/', and array_map('intval', $zni[0]);
Now the problem is i need to reverse those whole int to see if they are symmetric,like 555 and 66 , and if they are GET A TOTAL OF THEM.(total of only symmetric numbers)
i tried to use function " strrev "and got symmetric numbers, but i don't know how to put them in a one place IF THEY ARE symmetric and calculate them.
<?php
$numbers = "";
if (isset($_GET['submit']))
{
$numbers = ($_GET['niz']);
preg_match_all('/\d+/', $numbers, $zni);
$numtwo= array_map('intval', $zni[0]);
}
foreach ($numtwo as $num)
{
$reverse = strrev($num);
var_dump($reverse);
if ($num == $reverse)
{
$reverse = "true";
} else {
$reverse = "false";
}
var_dump($reverse);
}
Since you already got most of the way there and all you were missing basically was to use + or +=, here is an easy example on how to do it:
$input = "/43sdsd555ksldk66sd544fdfd";
$total = 0;
preg_match_all('/\d+/', $input, $m);
foreach ($m[0] as $d)
if ($d == strrev($d))
$total += $d;
var_dump($total); // => int(621)
Using intval() is not necessary as PHP will implicitly cast between types as needed.
Alternatively you can replace the loop with PHP's array_* functions:
$input = "/43sdsd555ksldk66sd544fdfd";
preg_match_all('/\d+/', $input, $m);
$total = array_sum(array_filter($m[0], function ($v) { return $v == strrev($v); }));
var_dump($total); // => int(621)
Here we use an anonymous function with array_filter() to generate a new array that only contains palindrome numbers from the original matches which is then given to array_sum().
So all that's needed to transform your original code into a working example, is introducing a variable and summing up:
<?php
$numbers = "";
if (isset($_GET['submit']))
{
$numbers = ($_GET['niz']);
preg_match_all('/\d+/', $numbers, $zni);
$numtwo= array_map('intval', $zni[0]);
}
$total = 0; // new variable
foreach ($numtwo as $num)
{
$reverse = strrev($num);
var_dump($reverse);
if ($num == $reverse)
{
$reverse = "true";
$total += $num; // sum up
} else {
$reverse = "false";
}
var_dump($reverse);
}
var_dump($total); // => int(621)

php array sorting with next value difference

can anyone help me with this following Array sorting
Input
$array=array(1,2,3,6,7,8,100,101,200);
Output:
$new_array=array(
0=>array(1,2,3),
1=>array(6,7,8),
2=>array(100,101),
3=>array(200)
);
Thanks in advance!
$array=array(1,2,3,6,7,8,100,101,200);
$new_array = array();
$lastNumber = '';
foreach($array as $number) {
if($lastNumber === '') {
$otherArray = array($number);
}
elseif($lastNumber + 1 !== $number) {
$new_array[] = $otherArray;
$otherArray = array($number);
}
else{
$otherArray[] = $number;
}
$lastNumber = $number;
}
$new_array[] = $otherArray;
print_r($new_array);
You can loop over the array and check the distance to the next element in the array. If this distance is larger then one add a new sub array:
$array=array(1,2,3,6,7,8,100,101,200);
$result=array(array());
for($i=0; $i<count($array)-1; $i++)
{
if($array[$i+1]-$array[$i]==1)
{
// If difference to next number is one -> push
array_push($result[count($result)-1], $array[$i]);
}
else
{
// ... else: Push and create new array for the next element
array_push($result[count($result)-1], $array[$i]);
array_push($result, array());
}
}
// Push the last number
array_push($result[count($result)-1], $array[$i]);
print_r($result);
Just a different approach with array_push()...
Pretty simple: loop through the numbers, remember the last one, if the current number is not the successor of the last one, add a new array to your result, push into the last array in your result.
$result = [];
$last = null;
foreach ($array as $number) {
if ($last !== $number - 1) {
$result[] = [];
}
$result[count($result) - 1][] = $number;
$last = $number;
}
You could even get rid of $last and directly read the last array element of the last array element of $result, but that would make the code actually more complicated.

Pair the elements in an array by two's then find the difference and sum

Let's say I have this array
$number = [2,1,4,3,6,2];
First pair the elements on an array by two's and find their difference
so this is the output in the first requirement
$diff[] = [1,1,4];
Second sum all the difference
this is the final output
$sum[] = [6];
Conditions:
the array size is always even
the first element in a pair is always greater than the second one, so their is no negative difference
What I've done so far is just counting the size of an array then after that I don't know how to pair them by two's. T_T
Is this possible in php? Is there a built in function to do it?
One line:
$number = [2,1,4,3,6,2];
$total = array_sum(array_map(function ($array) {
return current($array) - next($array);
}, array_chunk($number, 2)));
echo $total;
This should work fine:
<?
$number = array(2,1,4,3,6,2);
for($i=0;$i<count($number); $i+=2){
$dif[] = $number[$i] - $number[$i+1];
}
print_r($dif);
$sum = 0;
foreach ($dif as $item){
$sum += $item;
}
echo 'SUM = '.$sum;
?>
Working CODE
If you want all the different stages kept,
$numbers = [2,1,4,3,6,2];
$diff = [];
for($i=0,$c=count($numbers);$i<$c;$i+=2)
{
$diff[] = $numbers[$i]-$numbers[$i+1];
}
$sum = array_sum($diff);
Else, to just get the total and bypass the diff array:
$numbers = [2,1,4,3,6,2];
$total = 0;
for($i=0,$c=count($numbers);$i<$c;$i+=2)
{
$total += $numbers[$i]-$numbers[$i+1];
}
I have got this far it gives the required solution.
$arr = array(2,1,4,3,6,2);
$temp = 0;
$diff = array();
foreach ($arr as $key => $value) {
if($key % 2 == 0) {
$temp = $value;
}
else {
$diff[] = $temp - $value;
}
}
print_R($diff);
print 'Total :' . array_sum($diff);
Note : Please update if any one knows any pre-defined function than can sorten this code.
Please check and see if this works for you.
<?php
$sum=0;
$number = array(2,1,4,3,6,2);
for ($i=0;$i<=count($number);$i++) {
if ($i%2 == 1 ) {
$sum = $sum + $number[$i-1] - $number[$i];
}
}
print $sum;
?>
Well with your conditions in mind I came to the following
$number = [2,1,4,3,6,2];
$total = 0;
for($i = 0; $i < count($number); $i+=2) {
$total += $number[$i] - $number[$i + 1];
}
Try this one:
$number = array(2,1,4,3,6,2);
$diff = array();
$v3 = 0;
$i=1;
foreach($number as $val){
if ($i % 2 !== 0) {
$v1 = $val;
}
if ($i % 2 === 0) {
$v2 = $val;
$diff[] = $v1-$v2;
$v3+= $v1-$v2;
}
$i++;
}
print $v3;//total value
print_r($diff); //diff value array

calculate the arithmetic elements of php array?

this i my array
$arr = array(1,2,3,4,5);
How to get the result that calculate the value of this expression ((((1-2) -3)-4)-5)?
2 times the first entry minus the whole sum - looks pretty quick.
echo (2 * reset($arr)) - array_sum($arr);
Just substract the sum of all elements but the first from the first element:
echo array_shift($arr) - array_sum($arr); # -13
To preserve the array, change the calculation a little:
echo $arr[0]*2 - array_sum($arr); # -13
And we're glad you didn't ask for eval:
echo eval('return '.implode('-', $arr).';'); # -13
However the best suggestion I can give is that you encapsulate the logic into a class and overload the array with it. So that the object than can provide a method for the calculation (Demo):
class Operands extends ArrayObject
{
public function operate($sign)
{
$sign = max(-1, min(1, $sign.'1'));
$arr = $this->getArrayCopy ();
return $arr[0]*(1-$sign) + $sign*array_sum($arr);
}
public function __invoke($sign) {
return $this->operate($sign);
}
}
$arr = new Operands($arr);
echo $arr('-'), ', ' , $arr('+');
<?php echo eval(implode("-", $arr)); ?>
Try this:
$arr = array(1,2,3,4,5);
// load the first number to subtract
$result = $arr[0];
$i = 1;
foreach($arr as $item)
{
if ($i !=1) // skip the first one
$result -= $item;
$i++;
}
echo $result;
?>
This?
<?php
foreach ($arr as $val)
{
$calc -= $val;
}
echo $calc;
?>
Like #mOrSa, but more readable:
<?php
$arr = array(1, 2, 3, 4, 5);
// load the first number to subtract
$result = $arr[0];
for ($i = 1; $i < count($arr); $i++)
{
$result -= $arr[i];
}
echo $result;
?>

Categories