Create a recursive function with an array - php

I have a function but can't success to make it recursive.
This is my function without recursion :
function resolution_recursion($tab1, $tab2){
$solution = [];
foreach($tab2 as $nb2){
foreach($tab1 as $nb1){
if(($nb2 + $nb1)%2 != 1){
$solution[] = $nb2 + $nb1;
}
}
}
return $solution;
}
And I would like to make it recursive to make it work like :
$nb_ajout = [2];
$next = [[1,2],[3,4],[5,6],[7,8]];
resolution_recursion(
resolution_recursion(
resolution_recursion(
resolution_recursion($nb_ajout, $next[0]),
$next[1]),
$next[2]),
$next[3]);
I can't find the solution, if you can help me.

Something like this would do the trick...
function resolution_recursion($tab1, $tab2, $solution = [])
{
if (empty($tab2)) {
return $solution;
}
$set = array_shift($tab2);
foreach($set as $nb2){
foreach($tab1 as $nb1){
if(($nb2 + $nb1)%2 != 1){
$solution[] = $nb2 + $nb1;
}
}
}
if (!empty($tab2)) {
return resolution_recursion($tab1, $tab2, $solution);
}
return $solution;
}
You can find a demo here (the output however means absolutely nothing to me though so hopefully it means something to you lol)

I think I have found something, not using recursion :
function resolution_recursion($tab1, $tab2){
$solution = [];
$solution[-1] = $tab1;
foreach($tab2 as $key => $tab){
foreach($tab as $nb2){
foreach($solution[$key-1] as $nb1){
if(($nb2 + $nb1)%2 != 1){
$solution[$key][] = $nb2 + $nb1;
}
}
}
}
return $solution;
}

Related

string replace without using any in-built function

With a program to replace substring in a string without using str_replace
should be generic function should work for below example:
Word : Hello world
Replace word : llo
Replace by : zz
Output should be: Hezz world
Word : Hello world
Replace word : o
Replace by : xx
Output should be: Hellxx wxxrld
This is what i wrote to solve it
function stringreplace($str, $stringtoreplace, $stringreplaceby){
$i=0;$add='';
while($str[$i] != ''){
$add .= $str[$i];
$j=0;$m=$i;$l=$i;$check=0;
if($str[$i] == $stringtoreplace[$j]){
while($stringtoreplace[$j] != ''){
if($str[$m] == $stringtoreplace[$j]){
$check++;
}
$j++;$m++;
}
if($check == strlen($stringtoreplace)){
$n=0;$sub='';
for($n=0;$n<=strlen($stringtoreplace);$n++){
$str[$l] = '';
$sub .= $str[$l];
$l++;
}
$add .= $stringreplaceby;
$i += $check;
}
}
$i++;
}//echo $add;exit;
return $add;
}
I am getting output as helzzworld .
Please take a look what I did wrong or if you have better solution for this please suggest.
You can do this by explode the main string into array then implode your stringreplaceby to your array parts creating new string
<?php
function stringreplce($str,$strreplace,$strreplaceby){
$str_array=explode($strreplace,$str);
$newstr=implode($strreplaceby,$str_array);
return $newstr;
}
echo stringreplce("Hello World","llo","zz")."<br>";
echo stringreplce("Hello World","Hel","zz")."<br>";
echo stringreplce("Hello World"," Wo","zz")."<br>";
echo stringreplce("Hello World","rl","zz")."<br>";
echo stringreplce("Hello World","ld","zz")."<br>";
?>
Try this simplest one, without using str_replace, Here we are using explode and implode and substr_count.
1. substr_count for counting and checking the existence of substring.
2. explode for exploding string into array on the basis of matched substring.
3. implode joining the string with replacement.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$string="Hello world";
echo strReplace($string,"llo","zz");
echo strReplace($string,"o","xx");
function strReplace($string,$toReplace,$replacement)
{
if(substr_count($string, $toReplace))
{
$array=explode($toReplace,$string);
return implode($replacement, $array);
}
}
Solution 2:
Try this code snippet here not best, but working
<?php
ini_set('display_errors', 1);
$string="Hello world";
echo strReplace($string,"llo","zz");
echo strReplace($string,"o","xx");
function strReplace($string,$toReplace,$replacement)
{
while($indexArray=checkSubStringIndexes($toReplace,$string))
{
$stringArray= getChars($string);
$replaced=false;
$newString="";
foreach($stringArray as $key => $value)
{
if(!$replaced && in_array($key,$indexArray))
{
$newString=$newString.$replacement;
$replaced=true;
}
elseif(!in_array($key,$indexArray))
{
$newString=$newString.$value;
}
}
$string=$newString;
}
return $string;
}
function getLength($string)
{
$counter=0;
while(true)
{
if(isset($string[$counter]))
{
$counter++;
}
else
{
break;
}
}
return $counter;
}
function getChars($string)
{
$result=array();
$counter=0;
while(true)
{
if(isset($string[$counter]))
{
$result[]=$string[$counter];
$counter++;
}
else
{
break;
}
}
return $result;
}
function checkSubStringIndexes($toReplace,$string)
{
$counter=0;
$indexArray=array();
$newCounter=0;
$length= getLength($string);
$toReplacelength= getLength($toReplace);
$mainCharacters= getChars($string);
$toReplaceCharacters= getChars($toReplace);
for($x=0;$x<$length;$x++)
{
if($mainCharacters[$x]==$toReplaceCharacters[0])
{
for($y=0;$y<$toReplacelength;$y++)
{
if(isset($mainCharacters[$x+$y]) && $mainCharacters[$x+$y]==$toReplaceCharacters[$y])
{
$indexArray[]=$x+$y;
$newCounter++;
}
}
if($newCounter==$toReplacelength)
{
return $indexArray;
}
}
}
}
function ganti_kata($kata,$kata_awal,$kata_ganti){
$i =0; $hasil;
$panjang = strlen($kata);
while ($i < $panjang) {
if ($kata[$i] == $kata_awal) {
$hasil[$i] = $kata_ganti;
echo $hasil[$i];
}
else if ($kata[$i] !== $kata_awal){
$hasil[$i] = $kata[$i];
echo $hasil[$i];
}
$i++;
}
}
echo ganti_kata('Riowaldy Indrawan','a','x');
This code using php

A better way to check if GET isset and set variable?

Hello I'm having trouble thinking of a way to set custom variables with there $_GET counterpart in a cleaner way than below, this is a post-back for the url http://example.com/postback.php?id={offer_id}&offer={offer_name}&session={session_ip}&payout={payout} after running I get all $_GET with either their data or nil for all variables: $id, $offer, $session, $payout obviously i am a php newbie, please go easy on me! Thanks, any help would be great.
if (s('id')) {
$id = $_GET["id"];
} else {
$id = 'nil';
}
if (s('offer')) {
$offer = $_GET["offer"];
} else {
$offer = 'nil';
}
if (s('session')) {
$session = $_GET["session"];
} else {
$session = 'nil';
}
if (s('payout')) {
$payout = $_GET["payout"];
} else {
$payout = 'nil';
}
function s($name) {
if(isset($_GET["$name"]) && !empty($_GET["$name"])) {
return true;
}
return false;
}
Use extract: http://php.net/manual/de/function.extract.php
// Assuming $_GET = array('id' => 123, etc.)
extract($_GET);
var_dump($id);
// And later in your code
if (isset($id)) {
// Do what you need
}
maybe you can use a universal wrapper
<?php
function getValue($key, $fallback='nil') {
if(isset($_GET[$key]) $val = trim($_GET[$key]);
else $val = null;
return ($val) ? $val : $fallback;
}
and then you can handle it easyer by
<?php
$id = getValue('id'); ...
isset is not needed, and maybe you can use the ternary operator.
$id = !empty($_GET["id"]) ? $_GET["id"] : null;
$offer = !empty($_GET["offer"]) ? $_GET["offer"] : null;
$session = !empty($_GET["session"]) ? $_GET["session"] : null;
$payout = !empty($_GET["payout"]) ? $_GET["payout"] : null;

How to validate the return of a function based on conditional internal calls to other functions

I have a function, as shown in the code below, that should return true if the code is executed correctly. Nothing new.
The problem is that the function calls other functions, each returns true or false.
I'm trying to figure out how to construct the logic to validate the output of the function checking the code of the function itself, and the returns of the other functions. The other functions might be called or not, depending on the $this->conf['functionName'] parameter, which is also a boolean.
public function execute() {
$return = false;
if ($this->conf['functionOne']) {
$this->functionOne();
}
if ($this->conf['functionTwo']) {
$this->functionTwo();
}
if ($this->conf['functionThree']) {
$this->functionThree();
}
return $return;
}
I would do this
public function execute() {
$function_list = ['functionOne', 'functionTwo', 'functionThree'];
$return = true;
foreach ($function_list as $function) {
if ($this->conf[$function]) {
if (!$this->{$function}() && $return) {
$return = false;
}
}
}
return $return;
}
It's not quite clear but I think you mean something like this...
public function execute() {
$res1 = $res2 = $res3 = true;
if($this->conf['functionOne']){
$res1 = $this->functionOne();
}
if($this->conf['functionTwo']){
$res2 = $this->functionTwo();
}
if($this->conf['functionThree']){
$res3 = $this->functionThree();
}
return ($res1 && $res2 && $res3);
}
Do you mean this:
public function execute() {
$return = false;
if($this->conf['functionOne']){
$return = $this->functionOne();
}
if($this->conf['functionTwo']){
$return = $this->functionTwo();
}
if($this->conf['functionThree']){
$return = $this->functionThree();
}
return $return;
}
Is this works ?
public function execute() {
$f1 = $f2 = $f3 = false ;
if($this->conf['functionOne']){
$f1 = $this->functionOne();
}
if($this->conf['functionTwo']){
$f2 = $this->functionTwo();
}
if($this->conf['functionThree']){
$f3 = $this->functionThree();
}
if($f1=== true && $f2===true && $f3===true)
return true;
else
return false ;
}

Get return values of code with tokenizer

I'm trying to parse PHP source code with the token_get_all(). So far everything worked out with that function, but now i need a way to get the return values of methods.
Identifying where a return is done isn't the problem. I just see no way of getting the piece of code that comes after the return value.
For example for this piece of code:
<?php
class Bla {
public function Test1()
{
$t = true;
if($t) {
return 1;
}
return 0;
}
public function Test2()
{
echo "bbb";
return; // nothing is returned
}
public function Test3()
{
echo "ccc";
$someval1 = 1;
$someval2 = 2;
return ($someval + $otherval)*2;
}
}
?>
I'm using get_token_all() to identify where a return is done:
$newStr = '';
$returnToken = T_RETURN;
$tokens = token_get_all($source);
foreach ($tokens as $key => $token)
{
if (is_array($token))
{
if (($token[0] == $returnToken))
{
// found return, now get what is returned?
}
else
{
$token = $token[1];
}
}
$newStr .= $token;
}
I have no clue how to get the piece of code that is actually returned. That is what i want to get.
Anyone any idea how i could do this?
Perhaps this might help. Though I curious to know what you are ultimately trying to do.
$tokens = token_get_all($str);
$returnCode = '';
$returnCodes = array();
foreach ($tokens as $token) {
// If return statement start collecting code.
if (is_array($tokens) && $token['0'] == T_RETURN) {
$returnCode .= $token[1];
continue;
}
// if we started collecting code keep collecting.
if (!empty($returnCode)) {
// if we get to a semi-colon stop collecting code
if ($token === ';') {
$returnCodes[] = substr($returnCode, 6);
$returnCode = '';
} else {
$returnCode .= isset($token[1]) ? $token[1] : $token;
}
}
}

php regex failed, why?

The value is AbcDefg_123.
Here is the regex:
function checkAlphNum($alphanumeric) {
$return = false;
if((preg_match('/^[\w. \/:_-]+$/', $alphanumeric))) {
$return = true;
}
return $return;
}
Should allow a-zA-Z0-9.:_-/ and space in any order or format and does need all but at least one character.
EDIT: Sorry again, looks like var_dump() is my new best friend. I'm working with XML and it's passing the tag as well as the value.
#SilentGhost thnx for the tips.
It works for me too.
<?php
class RegexValidator
{
public function IsAlphaNumeric($alphanumeric)
{
return preg_match('/^[\w. \/:_-]+$/', $alphanumeric);
}
}
?>
and this is how I am testing it.
<?php
require_once('Classes/Utility.php');
$regexVal = new RegexValidator();
$list = array("abcd", "009aaa", "%%%%", "0000(", "aaaa7775aaa", "$$$$0099aaa", "kkdkdk", "aaaaa", "..0000", " ");
foreach($list as $value)
{
if($regexVal->IsAlphaNumeric($value))
{
echo $value . " ------>passed";
echo "<BR>";
}
else
{
echo $value . "------>failed";
echo "<br>";
}
}
?>
function checkAlphNum($alphanumeric) {
$return = false;
if((preg_match('/^[A-Za-z0-9\w. \/:_-]+$/', $alphanumeric))) {
$return = true;
}
return $return;
}
print checkAlphNum("AbcDefg_123");
Returns true.

Categories