why mycode after for loop is not executed? [duplicate] - php

This question already has answers here:
Code after a return statement in a PHP function
(3 answers)
Closed 6 months ago.
please check my code. i have some program to return the third largest word in a given array.
if in the third largest word has a same letters long, so retrun the last one.
for example ['world', 'hello', 'before', 'all', 'dr'] the output should be 'hello'.
my program is working fine, however when I want to echo the $result, the code doesn't execute.
here is my code:
<?php
$array = ['world', 'hello', 'before', 'all', 'dr'];
$array2 = [];
foreach ($array as $value) {
$array2[$value] = strlen($value);
}
asort($array2);
$slice = array_slice($array2, -3);
$array3 = [];
foreach ($slice as $key => $value) {
$array3[] = $key;
}
$result = "THIS RESULT SHOULD BE RE ASSIGNED, BUT WHY !!!!!";
for ($i = count($array3) - 1; $i >= 0; $i--) {
if ($i == 0) {
$result = $array3[$i];
return $result;
}
if (strlen($array3[$i]) == strlen($array3[$i - 1])) {
$result = $array3[$i];
return $result;
}
}
echo "THIS LINE IS NOT WORKING";
echo $result;

You have to use break instead of return.
<?php
$array = ['world', 'hello', 'before', 'all', 'dr'];
$array2 = [];
foreach ($array as $value) {
$array2[$value] = strlen($value);
}
asort($array2);
$slice = array_slice($array2, -3);
$array3 = [];
foreach ($slice as $key => $value) {
$array3[] = $key;
}
$result = "";
for ($i = count($array3) - 1; $i >= 0; $i--) {
if ($i == 0) {
$result = $array3[$i];
break;
}
if (strlen($array3[$i]) == strlen($array3[$i - 1])) {
$result = $array3[$i];
break;
}
}
echo $result;

Simply remove the return statements in the loop. instead of return, perhaps use break.

You can try this way as well.
<?php
/**
* Read more about here
* https://www.php.net/manual/en/function.usort.php
*/
function sort_by_length($a,$b){
return strlen($b)-strlen($a);
}
$array =['world', 'hello', 'before', 'all', 'dr'];
usort($array,'sort_by_length'); // sorting array with a custom function.
if(count($array) >= 2) {
$sliced = array_slice($array, 2);
$result = $sliced[0];
/**
* Read more at
* 1. https://www.php.net/manual/en/function.next.php
* 2. https://www.php.net/manual/en/function.current.php
*/
while(strlen(current($sliced)) == strlen(next($sliced))){
$result = current($sliced);
}
echo $result;
} else {
echo "Not enough items in array.";
}
This will output
hello

Remove the return .It return the value so any code after it will not be executed.

Related

Find unique (not repeating) combination php

I'm facing a technical problem here, I have an array [PER_DAY, PER_SIZE, PER_TYPE], I want to find combination all of the item without repeating the element, the result should be
[PER_DAY]
[PER_SIZE]
[PER_TYPE]
[PER_DAY, PER_SIZE]
[PER_DAY, PER_TYPE]
[PER_SIZE, PER_TYPE]
[PER_DAY, PER_SIZE, PER_TYPE]
This code repeating same value, so the result is too much.
$arr = ['PER_DAY', 'PER_SIZE', 'PER_TYPE'];
$result = [];
function combinations($arr, $level, &$result, $curr=[]) {
for($i = 0; $i < count($arr); $i++) {
$new = array_merge($curr, array($arr[$i]));
if($level == 1) {
sort($new);
if (!in_array($new, $result)) {
$result[] = $new;
}
} else {
combinations($arr, $level - 1, $result, $new);
}
}
}
for ($i = 0; $i<count($arr); $i++) {
combinations($arr, $i+1, $result);
}
This question possible duplicate, but I cannot found example similar like this, thanks.
function pc_array_power_set($array) {
// initialize by adding the empty set
$results = array(array( ));
foreach ($array as $element)
foreach ($results as $combination)
array_push($results, array_merge(array($element), $combination));
return array_filter($results);
}
$set = ['PER_DAY', 'PER_SIZE', 'PER_TYPE'];
$power_set = pc_array_power_set($set);
echo '<pre>';
print_r($power_set);
You have make combination from array, will help you :-PHP array combinations

How to recursively combine array in php

I want to combine two arrays into a dictionary.
The keys will be the distinct values of the first array, the values will be all values from the second array, at matching index positions of the key.
<?php
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
?>
array_combine($b,$a);
Expected result as
<?php
/*
Value '1' occurs at index 0, 1 and 4 in $b
Those indices map to values 2, 3 and 6 in $a
*/
$result=[1=>[2,3,6],3=>4,2=>[5,7],6=>8,8=>[9,10]];
?>
There are quite a few PHP array functions. I'm not aware of one that solves your specific problem. you might be able to use some combination of built in php array functions but it might take you a while to weed through your choices and put them together in the correct way. I would just write my own function.
Something like this:
function myCustomArrayFormatter($array1, $array2) {
$result = array();
$num_occurrences = array_count_values($array1);
foreach ($array1 AS $key => $var) {
if ($num_occurrences[$var] > 1) {
$result[$var][] = $array2[$key];
} else {
$result[$var] = $array2[$key];
}
}
return $result;
}
hope that helps.
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
$results = array();
for ($x = 0; $x < count($b); $x++) {
$index = $b[$x];
if(array_key_exists ($index, $results)){
$temp = $results[$index];
}else{
$temp = array();
}
$temp[] = $a[$x];
$results[$index] = $temp;
}
print_r($results);
Here's one way to do this:
$res = [];
foreach ($b as $b_index => $b_val) {
if (!empty($res[$b_val])) {
if (is_array($res[$b_val])) {
$res[$b_val][] = $a[$b_index];
} else {
$res[$b_val] = [$res[$b_val], $a[$b_index]];
}
} else {
$res[$b_val] = $a[$b_index];
}
}
var_dump($res);
UPDATE: another way to do this:
$val_to_index = array_combine($a, $b);
$result = [];
foreach ($val_to_index as $value => $index) {
if(empty($result[$index])){
$result[$index] = $value;
} else if(is_array($result[$index])){
$result[$index][] = $value;
} else {
$result[$index] = [$result[$index], $value];
}
}
var_dump($result);

Find first and last matching sequence in array php

I have a array to find sequence of alphabets and then fetch last and first combination. I am trying something like this.
$aarr = ['x','y','z','t','m','n','x','y','z'];
$str = implode('',$aarr);
$all_subset = powerSet($aarr);
foreach ($all_subset as $set) {
$sre_temp = implode('', $set);
$tru = hasOrderedCharactersForward($sre_temp);
if($tru){
echo $sre_temp.'<br>';
}
}
function powerSet($array) {
// add the empty set
$results = array(array());
foreach ($array as $element) {
foreach ($results as $combination) {
$results[] = array_merge(array($element), $combination);
}
}
return $results;
}
function hasOrderedCharactersForward($str, $i = 2) {
$alpha = 'abcdefghijklmnopqrstuvwxyz';
$len = strlen($str);
for($j=0; $j <= $len - $i; $j++){
if(strrpos($alpha, substr($str, $j, $i)) !== false){
return true;
}
}
return false;
}
I think powerSet() is not working like i think. Even it should show 'xyz' as combination but its not;
Have a look at this and make use of it if it fits your needs.
$aarr = ['x','y','z','t','m','n','x','y','z'];
$subsets = [];
$i=0;
#here we merge all chars to sub-sequence
foreach($aarr as $k=>$v){
$subsets[$i][]=$v;
if(isset($aarr[$k+1]) && ord($v)+1!==ord($aarr[$k+1])){
$i++;
}
}
$subsets = array_map(function($a){ return implode('',$a);},$subsets);
print_r($subsets);
Result:
Array ( [0] => xyz [1] => t [2] => mn [3] => xyz )
Getting the first and last value:
#get first
$first=null;
$i=0;
do{
if(strlen($subsets[$i])>1){#find sequence
$first = $subsets[$i];
}
$i++;
}while(!$first && isset($subsets[$i]));
#get last
$last=null;
$i=count($subsets)-1;
do{
if(strlen($subsets[$i])>1){#find sequence
$last = $subsets[$i];
}
$i--;
}while(!$last && isset($subsets[$i]));
print "$first, $last";
Result:
xyz, xyz

php find number range of array

i have an array like this:
$d=array('good'=>10,'very good'=>20,'bad'=>1);
i want to find key from it when 13 number closest vlaue of array.
for example 16 close to 20 in $d array .
like result:
key:very good
value:20
Code
$d=array('good'=>10,'very good'=>20,'bad'=>1);
$find=13;
foreach(array_chunk($find, 5) as $val) {
echo reset($val) . "-" . end($val);
}
sorry for my english.
This is not very pretty code, but I think it does what you want it to.
$d=array('good'=>10,'very good'=>20,'bad'=>1);
$closest = array('int' => -1, 'key' => null);
$find = 16;
foreach($d as $k=>$v) {
if ($closest['int'] == -1) { $closest['int'] = abs($find-$v); $closest['key'] = $k; continue; }
if (abs($find - $v) < $closest['int']) {
$closest['int'] = abs($find-$v);
$closest['key'] = $k;
}
}
echo "key:".$closest['key']."
value:".$d[$closest['key']];
You can try
$d = array('good' => 10,'very good' => 20,'bad' => 1);
vprintf("Find:%d, Closest: %d, Grade: %s\n",findClosest($d,13));
vprintf("Find:%d, Closest: %d, Grade: %s\n",findClosest($d,16));
Output
Find:13, Closest: 10, Grade: good
Find:16, Closest: 20, Grade: very good
Function Used
function findClosest($array, $find) {
$map = array_map(function ($v) use($find) {
return abs($v - $find);
}, $array);
asort($map);
return array($find,$array[key($map)],key($map));
}
try code
$d = array('good'=>10,'very good'=>20,'bad'=>1);
$find=13;
$result = get_closest($d , $find);
echo $result;
function get_closest($array = array(), $key){
$new_arr = array();
foreach($array AS $index=>$arr){
if($key < $arr) {
$new_arr[$index] = $arr - $key;
}
else{
$new_arr[$index] = $key - $arr;
}
}
$min_val = min($new_arr);
$res = array_search( $min_val , $new_arr);
return $res;
}
thanks
you can use array_values function to get all values as $a, then you can sort $a.After sort you can find two numbers between $find, then you can compare those two numbers.

how to write function Max($array) which returns the maximum value contained in $array or some array nested within $array

Eg:
$array= array(array(141,151,161),2,3,array(101,202,array(303,606)));
output :606
What you need is to recursively go through your array ; which means the max function, which is not recursive, will not be "enough".
But, if you take a look at the users's notes on the manual page of max, you'll find this note from tim, who proposes this recursive function (quoting) :
function multimax( $array ) {
// use foreach to iterate over our input array.
foreach( $array as $value ) {
// check if $value is an array...
if( is_array($value) ) {
// ... $value is an array so recursively pass it into multimax() to
// determine it's highest value.
$subvalue = multimax($value);
// if the returned $subvalue is greater than our current highest value,
// set it as our $return value.
if( $subvalue > $return ) {
$return = $subvalue;
}
} elseif($value > $return) {
// ... $value is not an array so set the return variable if it's greater
// than our highest value so far.
$return = $value;
}
}
// return (what should be) the highest value from any dimension.
return $return;
}
Using it on your array :
$arr= array(array(141,151,161),2,3,array(101,202,array(303,404)));
$max = multimax($arr);
var_dump($max);
Gives :
int 404
Of course, this will require a bit more testing -- but it should at least be a start.
(Going through the users' notes on manual pages is always a good idea : if you're having a problem, chances are someone else has already had that problem ;-) )
Same idea as Pascal's solution, only shorter thanks to the Standard PHP Library
$arr= array(array(141,151,161),2,3,array(101,202,array(303,404)));
echo rmax($arr);
function rmax(array $arr) {
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
// initialize $max
$it->next(); $max = $it->current();
// "iterate" over all values
foreach($it as $v) {
if ( $v > $max ) {
$max = $v;
}
}
return $max;
}
http://www.java2s.com/Code/Php/Data-Structure/FindtheMaximumValueinaMultidimensionalArray.htm
function recursive_array_max($a) {
foreach ($a as $value) {
if (is_array($value)) {
$value = recursive_array_max($value);
}
if (!(isset($max))) {
$max = $value;
} else {
$max = $value > $max ? $value : $max;
}
}
return $max;
}
$dimensional = array(
7,
array(3, 5),
array(5, 4, 7, array(3, 4, 6), 6),
14,
2,
array(5, 4, 3)
);
$max = recursive_array_max($dimensional);
$arr = array(array(141,151,161), 2, 3, array(101, 202, array(303,404)));
$callback = function ($value, $key) use (&$maximo) {
if( $value > $maximo){
$maximo = $value;
}
};
array_walk_recursive($arr, $callback);
echo '<pre>'; print_r($maximo);``
A more elegant solution:
function MaxArray($arr)
{
function findMax($currentValue, $currentKey)
{
global $maxValue;
$maxValue = ($currentValue > $maxValue ? $currentValue : $maxValue);
}
array_walk_recursive($arr, 'findMax');
return $GLOBALS['maxValue'];
}
It's very simple
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$max = max(iterator_to_array($iterator, false));
Finding the max avoiding too much recursion :
function array_max(array $array) {
$context = func_get_args();
$max = -INF;
while (!empty($context)) {
$array = array_pop($context);
while (!empty($array)) {
$value = array_pop($array);
if (is_array($value)) {
array_push($context, $value);
}
elseif ($max < $value) {
$max = $value;
}
}
}
return $max;
}
A more general method avoiding too much recursion :
function array_reduce_recursive($default, array $array, $callback = null) {
$context = func_get_args();
$count = func_num_args();
if (is_callable(func_get_arg($count - 1))) {
$callback = array_pop($context);
}
else {
$callback = create_function('$x, $y', 'return $x < $y ? $y : $x;');
}
$reduced = array_shift($context);
while (!empty($context)) {
$array = array_pop($context);
while (!empty($array)) {
$value = array_pop($array);
if (is_array($value)) {
array_push($context, $value);
}
else {
$reduced = $callback($reduced, $value);
}
}
}
return $reduced;
}
function array_max_recursive() {
$args = func_get_args();
$callback = create_function('$x, $y', 'return $x < $y ? $y : $x;');
return array_reduce_recursive(-INF, $args, $callback);
}
By this way you can specify the callback method if you are looking for something else than the biggest number. Also this method takes several arrays.
The end way is less efficient of course.
With this you have a full compatibility with lot of PHP version.
function MaxArray($arr) {
$maximum = 0;
foreach ($arr as $value) {
if (is_array($value)) {
//print_r($value);
$tmaximum = MaxArray($value);
if($tmaximum > $maximum){
$maximum = $tmaximum;
}
}
else
{
//echo $value.'\n';
if($value > $maximum){
$maximum = $value;
}
}
}
return $maximum;
}

Categories