PHP - best practice to call a function twice with a different param - php

I have the following function:
function sortRelevantId($idArray, $maxIds, $xml, $idTpe)
{
for ($i = count($idArray); $i < $maxIds; $i++) {
if ($xml->sub[$i]->type == $idTpe) {
$idArray[] = $i;
}
}
return $idArray;
}
I call these like so,
$idArray = [];
$idArray= sortRelevantId($idArray , $maxIds, $xml, "a");
$idArray= sortRelevantId($idArray , $maxIds, $xml, "b");
I am wondering how I can change the function so that I only need to call the function one and the logic in the function after type "a" and recall/ reruns for type "b" ("a" takes priority over "b")
Thanks for any help

You can change your codes as below.
function sortRelevantId($idArray, $maxIds, $xml, array $idTpe)
{
$idArray = array();
for ($i = count($idArray); $i < $maxIds; $i++) {
foreach($idTpe as $item) {
if ($xml->sub[$i]->type == $item) {
$idArray[] = $i;
}
}
}
return $idArray;
}
$idArray= sortRelevantId($idArray , $maxIds, $xml, array("a","b"));

You can use array_reduce for this by passing output of one result as input to the other and finally returning the value.
<?php
$idArray = array_reduce(["a", "b"], fn($carry, $item) => sortRelevantId($carry, $maxIds, $xml, $item), []);
print_r($idArray);

Related

How to count and print characters that occur at least Y times?

I want to count the number of occurrences of each character in a string and print the ones that occur at least Y times.
Example :
Examples func(X: string, Y: int):
func("UserGems",2) => ["s" => 2, "e" => 2]
func("UserGems",3) => []
This what I could achieve so far:
$str = "PHP is pretty fun!!";
$strArray = count_chars($str, 1);
$num = 1;
foreach ($strArray as $key => $value) {
if ($value = $num) {
echo "The character <b>'".chr($key)."'</b> was found $value time(s)
<br>";
}
}
Firstly, you need to list all letters count with separately and to calculate it. Also, you need to calculate elements equal to count which is your find. I wrote 3 types it for your:
<?php
function check($string,$count) {
$achives = [];
$strings = [];
$strArray = count_chars($string, 1);
if($count) {
foreach($strArray as $char => $cnt) {
if($cnt==$count) {
$achives[chr($char)] = $cnt;
}
}
}
return $achives;
}
echo '<pre>';
print_r(check("aa we are all theere Tural a1",1));
So, it is very short version
function check($string,$count = 1) {
$achives = [];
$strArray = count_chars($string, 1);
array_walk($strArray,function($cnt,$letter) use (&$achives,$count){
$cnt!==$count?:$achives[chr($letter)] = $cnt;
});
return $achives;
}
echo '<pre>';
print_r(check("aa we are all theere Tural a1",3));
But it is exactly answer for your question:
<?php
function check($string,$count) {
$achives = [];
$strings = [];
$strArray = str_split($string, 1);
foreach($strArray as $index => $char ){
$strings[$char] = isset($strings[$char])?++$strings[$char]:1;
}
if($count) {
foreach($strings as $char => $cnt) {
if($cnt==$count) {
$achives[$char] = $cnt;
}
}
}
return $achives;
}
<?php
function check($string,$count) {
$achives = [];
$strings = [];
$strArray = count_chars($string, 1);
if($count) {
foreach($strArray as $char => $cnt) {
if($cnt==$count) {
$achives[chr($char)] = $cnt;
}
}
}
return $achives;
}
echo '<pre>';
print_r(check("aa we are all theere Tural a1",1));
You can simply do this with php str_split() and array_count_values() built in functions. i.e.
$chars = str_split("Hello, World!");
$letterCountArray = array_count_values($chars);
foreach ($letterCountArray as $key => $value) {
echo "The character <b>'".$key."'</b> was found $value time(s)\n";
}
Output

PHP : How to remove a duplicate array item ONCE

I have an array:
$arr1 = [1,2,2,3,3,3];
Is there any method by which I can delete a duplicate value once like,
some_function($arr1,3);
which gives me the ouput $arr1 = [1,2,2,3,3]
As per the comment, check if there are more than one of the element you're searching for, then find and remove one of them.
function remove_one_duplicate( $arr, $target ) {
if( count( array_keys( $arr, $target ) ) > 1 ) {
unset( $arr[array_search( $target, $arr )] );
}
return $arr;
}
This should work...
function removeduplicate($myarray,$needle) {
if (($nmatches = count($matches = array_keys($myarray,$needle))) >= 2) {
for ($i=0; $i<$nmatches; $i++) {
if ($matches[$i+1] == (1+$matches[$i])) {
array_splice($myarray,$matches[$i],1);
break;
}
}
}
return $myarray;
}
To use the function...
$arr1 = [1,2,2,3,3,3,4,7,3,3];
$newarray = removeduplicate($arr1,3)
print_r($newarray);
EDITED:
If you want the function to modify your original array directly, you can do it (the function will return true if a character has been removed or false if not)...
function removeduplicate(&$myarray,$needle) {
if (($nmatches = count($matches = array_keys($myarray,$needle))) >= 2) {
for ($i=0; $i<$nmatches; $i++) {
if ($matches[$i+1] == (1+$matches[$i])) {
array_splice($myarray,$matches[$i],1);
return true;
}
}
}
return false;
}
So, now you can do...
$arr1 = [1,2,2,2,2,2,3,3,3,4,2,2];
removeduplicate($arr1,2);
print_r($arr1);
This function will copy the array skipping only the second instance of the specified element.
function removeOnce($array, $elem) {
$found = 0;
$result = [];
foreach ($array as $x) {
if ($x == $elem && (++$found) == 2) {
continue;
}
$result[] = $x;
}
return $result;
}

Increment returned integer in loop

How can I get the returned $i from the function getLast() and increment it in my foreach?
protected function getLast($array = [])
{
foreach($array as $file)
{
$getLast[] = substr($file, -5, 1);
}
$i = (int)$getLast[0];
return $i;
}
protected function foo()
{
$this->getLast($gl);
foreach($array as $img)
{
# ...
$i++;
}
}
You should assign the result of the function to a new variable.
protected function foo()
{
$i = $this->getLast($gl);
foreach($array as $img)
{
# ...
$i++;
}
}
But this will not be the same $i, it'll be another variable. I suppose you need a value, not a reference to the variable.
Your function returns a value - this is your i. So you only need to assing its return value in function occurence.
$i = $this->getLast($gl);
You can use reference to get the value of variable $i
Code:
protected function getLast($array = [], &$i)
{
foreach($array as $file)
{
$getLast[] = substr($file, -5, 1);
}
$i = (int)$getLast[0];
}
protected function foo()
{
$i = 0;
$this->getLast($gl, $i);
foreach($array as $img)
{
# ...
$i++;
}
}
in your situation $i = $this->getLast($gl);

Getting custom replace to work similar to how PHP PDO works

I just want to know how to replace a certain index character with an array constantly like how PDO works in PHP? Here is my code;
The the code
private $string;
public function __construct($string = null) {
if ($string !== null) {
$this->string = $string;
} else {
$this->string = '';
}
}
public function getString() {
return $this->string;
}
public function replaceWith($index, $array = array()) {
$lastArrayPoint = 0;
$i = 0;
while ($i < sizeof($this->string)) {
if (substr($this->string, $i, $i + 1) == $index) {
$newString[$i] = $array[$lastArrayPoint];
$i = $i . sizeof($array[$lastArrayPoint]);
$lastArrayPoint++;
} else {
$newString[$i] = $this->string[$i];
}
$i++;
}
return $this;
}
and the executing code
$string = new CustomString("if ? == true then do ?");
$string->replaceWith('?', array("mango", "print MANGO"));
echo '<li><pre>' . $string->getString() . '</pre></li>';
Thank you for the help I hope I will recieve.
$string = "if %s == true then do %s. Escaping %% is out of the box.";
$string = vsprintf($string, array("mango", "print MANGO"));
echo "<li><pre>$string</pre></li>";
str_replace has an optional count parameter, so you can make it replace one occurrance at a time. You can just loop through the array, and replace the next question mark for element N.
$string = "if %s == true then do %s";
$params = array("mango", "print MANGO");
foreach ($params as $param)
$string = str_replace('?', $param, $string, 1);
Thanks for the help guys but they did not work the way I wanted it to work. I have found a way to get it too work. Here is the code
public function replaceWith($index, $array = array()) {
$arrayPoint = 0;
$i = 0;
$newString = "";
while ($i < strlen($this->string)) {
if (substr($this->string, $i, 1) === $index) {
$newString .= $array[$arrayPoint];
$arrayPoint++;
} else {
$newString .= substr($this->string, $i, 1);
}
$i++;
}
$this->string = $newString;
return $this;
}
if anyone has a better way then you can tell me but for now this works.

Search array - PHPExcel

I'm using PHPExcel, I have an multidimensional array called $sheetData. I want to be able to search the array for string D650.
For example if the string D650 is in $sheetData[12][E] I want it to return [12][E]. I can't seem to find a search function for PHPExcel. I've tried the code below but I am only getting one value back I need all the values. If the code isn't the best way to go about this please let me know. Thanks
function searchForId($id, $array) {
foreach ($array as $key => $val) {
$letter = "A";
for($i = 1; $i<= 26; $i++)
{
if ($val[$letter] === $id) {
return $key;
}
$letter++;
}
}
return null;
}
$id = searchForId('Denter code here650', $sheetData);
echo $id;
function searchForId($id, $array) {
foreach ($array as $row => $val) {
$letter = "A";
for($i = 1; $i<= 26; $i++) {
if ($val[$letter] === $id) {
return '[' . $row .'][' . $letter . ']';
}
$letter++;
}
}
return null;
}
though it might be more useful returning an array of row and column
function searchForId($id, $array) {
foreach ($array as $row => $val) {
$letter = "A";
for($i = 1; $i<= 26; $i++) {
if ($val[$letter] === $id) {
return array(
'row' => $row,
'column' => $letter
);
}
$letter++;
}
}
return null;
}

Categories