Array in a recursive function - php

I have this recursive function in which I must use an array for memory and verification of used data, meaning, after a string has been used i would like to remember that it has been used so i will not go over that string again in the next iteration.
The problem is after the first iteration the array is considered NULL.
So my question is this : How do i pass an array in a recursive function ? or how do i work with arrays in recursive function?
I looked this up here and though there are many similar questions none answer my one.
Note: I understand that anything that can be done with recursion can be done with a loop... yet... this is the function. And like i mentioned on the 2nd iteration the array is considered to be NULL and i get this warning:
array_push() expects parameter 1 to be array, null given in...
Here is the logic of the function:
// Set Vars...
$Str = 'someData';
$S_Array = array();
// initial call...
GetData($Str, $S_Array);
function GetData ($string, $array)
{
// string manipulations code...
.
.
.
.
// Attempt to Store in array
array_push($array, $string);
foreach ($array as $val) {
// Recursive Call...
GetData($val, $array);
}
}

You are using array_push wrong -- the order of the arguments is switched. And there's really no need to use array_push at all, since the same result can be achieved with
$array[] = $string;

Related

How to test if array has empty value in it?

I have an array that I want to test for empty elements, I have tried using array_walk to walk an array (a single dimension array) and return true if the array of elements (values) has got any empty elements.
I naturally went to the PHP website, looked at the examples on offer and they don't make any sense because it does not give a clear example of how you would use array_walk for this. I tried array_filter and that didn't seem to do much either.
Example of what I was trying to do.
$test = array("Tree"=>"Ash","TreeID"=>"Q23-123","count"=>14,"User"=>"P.Williams");
$result = array_walk( $test, "empty", true );
All I get as a result is "Array".
and PHP parser is having a hissy fit about it, they say clearly, bool array_walk ( array &$array , callable $callback [, mixed $userdata = NULL ] ) in their site, this I deduced to be something $result array_walk ( $theTargetArray, "StringNameOfFunction", theResultIfTure); but nothing is that simple.
So far I have found lots of examples on many sites and it seems that people have just copied and pasted the PHP examples, some have changed their names to hide that they have copied and pasted the example...
Can someone let me know what it is that I am doing wrong here please?
(Also FAO stackoverflow site maintainers, What is the point in suggesting a tag, I click to use it and then I get told I can not create a new tag unless I have 1500 points??? Seriously Why? Good idea if you go and think about that one.)
$my_arr = array(....); // your array here
$has_empty_value = sizeof($my_arr) != sizeof(array_filter($my_arr));
array_walk is not going to help you on that. It's a mutator function, and is intended to change array elements, not to retrieve information about them. What you're looking for is a boolean aggregator function known as any or some in other languages. PHP doesn't provide it out of the box, so you have to write it by hand:
function any($iter, $pred) {
foreach($iter as $item)
if($pred($item))
return true;
return false;
}
However, an attempt to use it with empty, as in
print any($test, 'empty')
will fail, because empty is not a real function and can't be used indirectly. A workaround is to wrap it in yet another function and pass that one to any:
any($test, function($x) { return empty($x); })
Another option is to filter an array through boolval, thus removing "falsy" values, and compare lengths:
$hasEmptyElements = count(array_filter($test, 'boolval')) < count($test);
Note that, unlike any, which is "lazy", filter always processes the whole array.
The docs for array_walk say "Applies the user-defined callback function to each element of the array array." Therefore, you can use it with your own callbacks or with with a closure, like so:
$test = array("Tree"=>"Ash","TreeID"=>"Q23-123", "count"=> 14, "User"=>"P.Williams");
$result = array_walk( $test, function($value) {
return empty($value);
});
Of course, this depends on what you are trying to achieve as this will loop through all the values and $result will be true if all the values are empty but the last one is not.
If you are looking to find out if any of the values are empty, a function that stops after it finds an empty item would be better:
function hasEmptyValues(array $array)
{
foreach ($array as $key => $value) {
if (empty($value)) {
//Empty value found
return true;
}
}
//None of the values are empty
return false;
}

passing indefinite number of arguments to function without using an array

I am having situation where i want to pass variables in php function.
The number of arguments are indefinite. I have to pass in the function without using the array.
Just like normal approach. Comma Separated.
like test(argum1,argum2,argum3.....,..,,.,.,.....);
How i will call the function? Suppose i have an array array(1,2,3,4,5) containing 5 parameters. i want to call the function like func(1,2,3,4,5) . But the question is that, How i will run the loop of arguments , When calling the function. I tried func(implode(',',array)); But it is taking all return string as a one parameters
In the definition, I also want the same format.
I can pass variable number of arguments via array but i have to pass comma separated.
I have to pass comma separated. But at the time of passing i don't know the number of arguments , They are in array.
At the calling side, use call_user_func_array.
Inside the function, use func_get_args.
Since this way you're just turning an array into arguments into an array, I doubt the wisdom of this though. Either function is fine if you have an unknown number of parameters either when calling or receiving. If it's dynamic on both ends, why not just pass the array directly?!
you can use :
$function_args = func_get_args();
inside your test() function definition .
You can just define your function as
function test ()
then use the func_get_args function in php.
Then you can deal with the arguments as an array.
Example
function reverseConcat(){
return implode (" ", array_reverse(func_get_args()));
}
echo reverseConcat("World", "Hello"); // echos Hello World
If you truely want to deal with them as though they where named parameters you could do something like this.
function getDistance(){
$params = array("x1", "y1", "x2", "y2");
$args = func_get_args();
// trim excess params
if (count($args) > count($params) {
$args = array_slice(0, count($params));
} elseif (count($args) < count($params)){
// define missing parameters as empty string
$args = array_pad($args, count($params), "");
}
extract (array_combine($params, $args));
return sqrt(pow(abs($x1-$x2),2) + pow(abs($y1-$y2),2));
}
use this function:
function test() {
$args = func_get_args();
foreach ($args as $arg) {
echo "Arg: $arg\n";
}
}
I'm not sure what you mean by "same format." Do you mean same type, like they all have to be a string? Or do you mean they need to all have to meet some criteria, like if it's a list of phone numbers they need to be (ddd) ddd-dddd?
If it's the latter, you'll have just as much trouble with pre-defined arguments, so I'll assume you mean you want them all to be the same type.
So, going off of the already suggested solution of using func_get_args(), I would also apply array_filter() to ensure the type:
function set_names() {
function string_only($arg) {
return(is_string($arg));
}
$names_provided = func_get_args();
// Now you have an array of the args provided
$names_provided_clean = array_filter($names_provided, "string_only");
// This pulls out any non-string args
$names = array_values($names_provided_clean);
// Because array_filter doesn't reindex, this will reset numbering for array.
foreach($names as $name) {
echo $name;
echo PHP_EOL;
}
}
set_names("Joe", "Bill", 45, array(1,2,3), "Jane");
Notice that I don't do any deeper sanity-checks, so there could be issues if no values are passed in, etc.
You can use array also using explode http://www.php.net/manual/en/function.explode.php.
$separator = ",";
$prepareArray = explode ( $separator , '$argum1,$argum2,$argum3');
but be careful, $argum1,$argum2, etc should not contain , in value. You can overcome this by adding any separator. $separator = "VeryUniqueSeparator";
I don't have code so can't tell exact code. But manipulating this will work as your requirements.

PHP Array Search - key => string

I got some trouble with in_array()
$list = array(
"files/" => "/system/application/files/_index.php",
"misc/chat/" => "/system/application/misc/chat/_index.php"
);
I have this $_GET['f'] which holds the string files/.
How can I search through the array for possible matches?
If the string is found in the array, then the file should be included
Thanks for any help :)
It's really simple. All you need to do is check if the array element is set. The language construct that's usually used is isset() (yes, it's that obvious)...
if (isset($list[$_GET['f']])) {
}
There's no need to call a function for this, isset is cleaner and easier to read (IMHO)...
Note that isset is not actually a function. It's a language construct. That has a few implications:
You can't use isset on the return from a function (isset(foo()) won't work). It will only work on a variable (or a composition of variables such as array accessing or object accessing).
It doesn't have the overhead of a function call, so it's always fast. The overall overhead of a function call is a micro-optimization to worry about, but it's worth mentioning if you're in a tight loop, it can add up.
You can't call isset as a variable function. This won't work:
$func = 'isset';
$func($var);
array_key_exists is a function that returns true of the supplied key is in the array.
if(array_key_exists( $_GET['f'], $list )) {
echo $list[$_GET['f']];
}
You can use in_array() in conjunction with array_keys():
if (in_array($_GET['f'], array_keys($list))) {
// it's in the array
}
array_keys() returns an array of the keys from its input array. Using $list as input, it would produce:
array("files/", "misc/chat/");
Then you use in_array() to search the output from array_keys().
Use array_key_exists.
if(array_key_exists($_GET['f'], $list)){
// Do something with $list[$_GET['f']];
}
in_array() searches array for key using loose comparison unless strict is set.
it's like below.
foreach ($array as $value){
if ($key == $value){
return true;
}
}
My way.
function include_in_array($key, $array)
{
foreach($array as $value){
if ( strpos($value, $key) !== false ){
return false;
}
}
}

how to delete item from an array with filter?

I want to filter and delete an item from an array. is it possible to do it with array_filter() ?
//I want to delete these items from the $arr_codes
$id = 1223;
$pin = 35;
//Before
$arr_codes = Array('1598_9','1223_35','1245_3','1227_11', '1223_56');
//After
$arr_codes = Array('1598_9','1245_3','1227_11', '1223_56');
Thanks!
You can find the index of the value you are interested in with array_search and then unset it.
$i = array_search('1223_35',$arr_codes);
if($i !== false) unset($arr_codes[$i]);
array_filter does not take userdata (parameters). array_walk() does. However, none of the iterator function allow modifying the array structure within the callback.
As such, array_filter() is the appropriate function to use. However, since your comparison data is dynamic (per your comment), you're going to need another way to obtain comparison data. This could be a function, global variable, or build a quick class and set a property.
Here is an example using a function.
array_filter($arr, "my_callback");
function my_callback($val) {
return !in_array($val, get_dynamic_codes());
}
function get_dynamic_codes() {
// returns an array of bad codes, i.e. array('1223_35', '1234_56', ...)
}

Check if an array contains a specific value?

I'd like to check if there is a value on an array like this:
function check_value_new ($list, $message) {
foreach ($list as $current) {
if ($current == $message) return true;
}
return false;
}
function check_value_old ($list, $message) {
for ($i = 0; $i < count ($status_list); $i ++) {
if ($status_list[$i] == $$message) return true;
}
return false;
}
$arr = array ("hello", "good bye", "ciao", "buenas dias", "bon jour");
check_value_old ($arr, "buenas dias"); // works but it isn't the best
check_value_new ($arr, "buenas dias"); // argument error, where I'm wrong?
I've read the check_value_new method is a better way to work with arrays, but I'm not used to work with it, how I should fix it?
PHP offers a function called in_array that checks if a value exists in a given array.
You can change your check_value_new function to include this:
function check_value_new ($list, $message) {
foreach ($list as $current) {
if (in_array($message, $current)) {
return true;
}
return false;
}
If you'd like to, you could also make the function work without the foreach loop, like so
function check_value_new ($list, $message) {
// returns true if found, else returns false.
return in_array($message, $list);
}
The reasons that your check_value_old() function breaks is because you have a typo in your loop's second parameter. $status_list is not one of the variables passed into your function and it is not declared anywhere before it is used. You merely need to use $list instead. It is also not necessary to call count() on every iteration -- since that value never changes in the loop, just call it once before the loop and use that value in the second parameter.
As for deciding how to loop over array values, there is no reason to reinvent a native function call. in_array() was already designed and optimized to search linear values in an array and return true as soon as it finds a match; otherwise it returns false.
I don't know what #AnthonyForloney is doing by writing in_array() inside of a foreach() loop. Not only will the snippet break because there aren't enough curly braces, the input array does not have two levels of data, so in_array() will choke when it receives $current which is a string (not the expected array).
Ultimately, my advice is: Only write your own custom function when there isn't a native function to suit your needs. Throw away both of the manual looping ideas and only call:
$arr = ["hello", "good bye", "ciao", "buenas dias", "bon jour"];
var_export(in_array("buenas dias", $arr));
One final insight that I'd like to provide is regarding microoptimization. If you are planning to check the existence of a unique value in a "very large" array, or if you are going to be making thousands of searches on the same array, then it would be more efficient to set up your array in a "flipped" orientation and call isset() or array_key_exists(). isset()/array_key_exists() will always outperform in_array() or array_search() because of the way that php handles arrays as "hash maps". More reading here.

Categories