Multiple optional argument in a function - php

getAllForms($data=null)
getAllForms() and getAllForms("data")
This will work. But I want to make two optional argument in a function like this:
getAllForms($arg1=null,$arg2=null)
getAllForms() and getAllForms("data")
How can I make this possible?

You can try:
function getAllForms() {
extract(func_get_args(), EXTR_PREFIX_ALL, "data");
}
getAllForms();
getAllForms("a"); // $data_0 = a
getAllForms("a", "b"); // $data_0 = a $data_1 = b
getAllForms(null, null, "c"); // $data_0 = null $data_1 = null, $data_2 = c

You can also try using func_get_arg which you can pass n number of arguments to a function.
http://php.net/manual/en/function.func-get-args.php
Example
function foo(){
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
foo(1, 2, 3);

Try this:
getAllForms($data=null,$data2=null)
and you call it in this mode:
getAllForms()
getAllForms("data")
getAllForms("data","data2")
The second argument have to be different name respect the first

You already described how you would do it:
function getAllForms($arg1 = null, $arg2 = null)
Except the every variable name (including the second) has to be different.

<? php
function getAllForms($data1 = null, $data2 = null)
{
if ($data1 != null)
{
// do something with $data1
}
if ($data2 != null)
{
// do something with $data2
}
}
?>
getAllForms();
getAllForms("a");
getAllForms(null, "b");
getAllForms("a", "b");
or
<? php
function getAllForms($data = null)
{
if (is_array($data))
{
foreach($data as $item)
{
getAllForms($item);
}
}
else
{
if ($data != null)
{
// do something with data.
}
}
}
getAllForms();
getAllForms("a");
getAllForms(array("a"));
getAllForms(array("a", "b"));
?>

Related

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

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);

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.

Key exist in complexe array

I would like to test if the key of an associative array exist in my $_POST.
my $_POST is like that:
$_POST["balle"]["x"] = 5;
$_POST["balle"]["y"] = 5;
$_POST["balle"]["z"] = 5;
or like that by example:
$_POST["p1"][1]["vit"] = 7;
$_POST["p1"][1]["angle"] = 32;
$_POST["p2"][2]["vit"] = 17;
$_POST["p2"][2]["angle"] = 2;
the values don't matter but I must check how are my $_POST keys.
I don't understand how i can test recursivly that because the $_POST can change and have differents forms.
I have try this:
function Check_post($new, $arr)
{
echo "Init<br/>";
$res = true;
if (is_array($new))
{
foreach ($new as $key => $value)
{
if (!in_array($key, $arr))
{
echo "Fail $key";
print_r($arr);
return (false);
}
$res = $res & Check_post($new[$key], $arr[$key]);
}
}
else
$res = in_array($new, $arr);
echo "MY RESULT";
var_dump($res);
return ($res);
}
$b = array();
$b["balle"] = array("x", "y", "z");
$post = array();
$post["balle"] = array();
$post["balle"]["x"] = 50;
$post["balle"]["y"] = 50;
$post["balle"]["z"] = 50;
echo "<pre>";
print_r($b);
echo "</pre><pre>";
print_r($post);
echo "</pre>";
Check_post($b, $post);
but i got "Fail balle". my $post variable is to simulate the real $_POST and for make it easier to test.
EDIT:
The function should work like that:
1) test if "balle" exist in $post
2) "balle" exist so recursive call
3) test if "x" exist in $post["balle"](recursive)
4) test if "y" exist in $post["balle"](recursive)
5) test if "z" exist in $post["balle"](recursive)
6) all existe so $res = true
EDIT:
I finaly editet the whole function:
function Check_post($needle, $haystack)
{
if(is_array($needle)){
foreach ($needle as $key => $element){
$result = true;
if($result = (array_key_exists($key, $haystack) || array_key_exists($element, $haystack))){
$key = (isset($haystack[$key]) ? $key : $element);
if(is_array($haystack[$key]))
$result = Check_post($element, $haystack[$key]);
}
if(!$result){
return false;
}
}
return $result;
}else {
return array_key_exists($needle, $haystack);
}
}
Now it should work as you want it
Example:
$_POST["balle"]["x"] = 5;
$_POST["balle"]["y"] = 5;
$_POST["balle"]["z"] = 5;
$b = array();
$b["balle"] = array("x", "y", "z");
var_dump(Check_post($b, $_POST)); //returns true
$b["balle"] = array("x", "y", "z", "b");
var_dump(Check_post($b, $_POST)); //returns false
The in_array function you're using checks if $key is contained in $arr as a value. If I got you right, you want to check if there is the same key in $arr instead. Use array_key_exists($key, $arr) for this.
Try this
$_POST["p1"][1]["vit"] = 7;
$_POST["p1"][1]["angle"] = 32;
$_POST["p2"][2]["vit"] = 17;
$_POST["p2"][2]["angle"] = 2;
$needle = "2";
$samp = Check_post($_POST,$needle);
echo $samp;
function Check_post($array,$needle)
{
if(is_array($array))
{
foreach($array as $key=>$value)
{
if($key == $needle)
{
echo $key." key exists ";
}
else
{
if(is_array($value))
{
check_post($value,$needle);
}
}
}
}
}
Demo

PHP function varying parameters

I couldn't find about my issue on google and SO. Hope, i can explain you.
You'll understand when looked following function:
function get_page($identity)
{
if($identity is id)
$page = $this->get_page_from_model_by_id($identity);
elseif($identity is alias)
$page = $this->get_page_from_model_by_alias($identity);
}
My used function:
get_page(5); // with id
or
get_page('about-us'); // with alias
or
get_page(5, 'about-us'); // with both
I want to send parameter to function id or alias. It should be only one identifier.
I dont want like function get_page($id, $alias)
How can i get and know parameter type with only one variable. Is there any function or it possible?
if(is_numeric($identity)) {
$page = $this->get_page_from_model_by_id($identity);
}
elseif(is_string($identity)) {
$page = $this->get_page_from_model_by_alias($identity);
}
elseif(func_num_args() === 2) {
$id = func_get_arg(0);
$alias = func_get_arg(1);
//do stuff
}
Use is_string() to find whether input is integer or character.
You should make use of func_get_args()
<?php
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs<br />\n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "<br />\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
foo(1, 2, 3);
?>
Source
Here's a complete solution:
function get_page()
{
$alias = false;
$id = false;
foreach(func_get_args() as $arg)
if(is_string($arg))
$alias = $arg;
else if(is_int($arg))
$id = $arg;
}
Assuming id is always a number, you could test for it with php's is_numeric()
function get_page($identity)
{
if(is_numeric($identity) {
$page = $this->get_page_from_model_by_id($identity);
} else {
$page = $this->get_page_from_model_by_alias($identity);
}
}

Categories