Call a function within a function display both within array - php

how do I call a function from within a function?
function tt($data,$s,$t){
$data=$data;
echo '[[';
print_r($data);
echo ']]';
if($t==0){
$data[]=$s;
tt($data,'two',1);
}else{
$data[]=$s;
}
return $data;
}
print_r(tt('','one',0));
I want 'two' to be shown within the array like
$o[]='one';
$o[]='two';
print_r($o);

function tt($s, $t, array $data = array()) {
$data[] = $s;
if ($t == 0) {
$data = tt('two', 1, $data);
}
return $data;
}
print_r(tt('one', 0));
This is all that's really needed.
Put the array as the last argument and make it optional, because you don't need it on the initial call.
When calling tt recursively, you need to "catch" its return data, otherwise the recursive call simply does nothing of lasting value.
No need for the else, since you're going to append the entry to the array no matter what and don't need to write that twice.

Try this one (notice the function signature, the array is passed by ref &$data):
function tt(&$data,$s,$t){
echo '[[';
print_r($data);
echo ']]';
if($t==0){
$data[]=$s;
tt($data,'two',1);
}else{
$data[]=$s;
}
return $data;
}
$array = [];
tt($array,'one',0);
print_r($array);
/**
Array
(
[0] => one
[1] => two
)
*/

try this
function tt($data,$s,$t){
global $data;
if($t==0){
$data[]=$s;
tt($data,'two',1);
}else{
$data[]=$s;
}
return $data;
}
print_r(tt('','one',0));
OUTPUT :
Array
(
[0] => one
[1] => two
)
DEMO

Related

How to do an array merge between two functions?

I'm trying to get an array_merge but I can't. Calling the example.php file must also embed the array of the Usage_Module function.
Note: The getFunctionModule function must not be changed.
Surely I'm wrong something in the Usage_Module function, can you help me understand what I'm wrong?
Code example.php
function getFunctionModule() {
require "module.php";
$func = "Usage_Module";
if (!function_exists($func)) {
echo "function not found";
}
return (array) $func();
}
$data = ['status' => 'ok'];
$data = array_merge(getFunctionModule(), $data);
print_r($data);
Code module.php
function Usage_Module()
{
$data = ['licensekey2' => 'ok'];
return (array) $data;
}

how to add elements to an array inside a function php

how to add elements to a global array from inside a function if element not exist in array?
my main code will call to function multiple times.but each time different elements will create inside the function
my sample current code is,
$all=[];
t(); // 1st call
t(); //2nd call
function t(){
$d='2,3,3,4,4,4'; //this is a sample.but element will different for each function calling
$d=explode(',',$d);
foreach($d as $e){
if(!in_array($e,$all)){
array_push($all, $e);
}
}
}
print_r($all);
output is empty,
Array()
but i need it like this
Array
(
[0] => 2
[1] => 3
[2] => 4
)
thank you
If you look at the variable scope in PHP http://php.net/manual/en/language.variables.scope.php
You'll see that functions don't have access to the outer scope.
Therefore you'll need to do either pass the array by reference:
function t(&$myarray)
Create an array inside of the function and returning that one
function t(){
$all = [];
$d='2,3,3,4,4,4';
$d=explode(',',$d);
foreach($d as $e){
if(!in_array($e,$all)){
array_push($all, $e);
}
}
return $all;
}
Or if you want to keep adding to the array you can do
function t($all){
$d='2,3,3,4,4,4';
$d=explode(',',$d);
foreach($d as $e){
if(!in_array($e,$all)){
array_push($all, $e);
}
}
return $all;
}
Then calling the function with $all = t($all);
Your code will show errors as $all isn't in the scope of the function, you need to pass the value in to have any effect...
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$all=[];
t($all); // 1st call
t($all); //2nd call
function t( &$data){
$d='2,3,3,4,4,4'; //this is a sample.but element will different for each function calling
$d=explode(',',$d);
foreach($d as $e){
if(!in_array($e,$data)){
array_push($data, $e);
}
}
}
print_r($all);
Result
Array
(
[0] => 2
[1] => 3
[2] => 4
)
You can use global, but this is generally discouraged.
To add on Alexy's response regarding the use of 'array_unique($d)', which I recommend as it eliminates the need for the loop. You can pass the filtered array to array_values($d) to index your elements as shown by the results you want to achieve. FYI: array_unique will preserve the original keys: http://php.net/manual/en/function.array-unique.php
Your case will require removing duplicates a few times its best to have a separate function for that:
$all = [];
function t(){
global $all;//Tell PHP that we are referencing the global $all variable
$d='2,3,3,4,4,4';
$d=explode(',',$d);
$d=rmvDuplicates($d);
$all = array_merge($all,$d);//Combine the new array with what we already had
$all = rmvDuplicates($all);
}
function rmvDuplicates(array){
$array=array_unique($d);
$array=array_values($d);
return $array;
}

How to check if specific value exists in side an array?

I have the following sample function.
class EquipmentReport extends MY_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('Reporting/ReportModel');//load report model
$this->load->helper('url');
$this->load->helper('form');
$this->Authorize(); // method inherited and returns array
}
/**
* loads view if no $_POST data
* if post data generates sql query
* #return (query)
**/
public function by_category (){
$my_array = $this->Authorize();
if (in_array("USER_GROUP_STATUS", $my_array)) {
echo "Got USER_GROUP_STATUS";
}
}
dumping $my_array gives the following array
Array (
[0] => 'ALL',
'USER_GROUP_STATUS',
'USER_GROUP_HAS_PERMISSION_CREATE_DEPARTMENT',
'USER_GROUP_HAS_PERMISSION_READ_DEPARTMENT',
'USER_GROUP_HAS_PERMISSION_UPDATE_DEPART'
)
but checking array keys is nt working.
what I wanted to do is to check if the one of the values exist. for example if 'USER_GROUP_STATUS' exists in the array ?
Try this in_array() function
if (in_array("USER_GROUP_STATUS", $your_array)) {
echo "Got USER_GROUP_STATUS";
}
or You can try this way
$ary = [
0 => ['ALL', 'USER_GROUP_STATUS', 'USER_GROUP_HAS_PERMISSION_CREATE_DEPARTMENT',
'USER_GROUP_HAS_PERMISSION_READ_DEPARTMENT',
'USER_GROUP_HAS_PERMISSION_UPDATE_DEPART']
];
foreach($ary as $ar)
if (in_array("USER_GROUP_STATUS", $ar)) {
echo "Got USER_GROUP_STATUS";
}
Live Demo
Simply use in_array() :
if (in_array($string, $Arr)) {
//code
}
$yourArray = Array ( [0] => ALL,'USER_GROUP_STATUS','USER_GROUP_HAS_PERMISSION_CREATE_DEPARTMENT','USER_GROUP_HAS_PERMISSION_READ_DEPARTMENT','USER_GROUP_HAS_PERMISSION_UPDATE_DEPART' );
$needle = 'USER_GROUP_STATUS';
if(in_array($needle, $yourArray)) {
echo 'found it!';
}
Hope this helps you.
do sth like this
public function by_category()
{
$key= "USER_GROUP_STATUS";
$my_array = $this->Authorize();
if(in_array($key,$my_array)) {
echo 'Bravo!';
die();
}
}

Get the last dimension of each element of an array

I have an array that might be any depth or number of elements:
$ra['a'] = 'one';
$ra['b']['two'] = 'b2';
$ra['c']['two']['three'] = 'c23';
$ra['c']['two']['four'] = 'c24';
$ra['c']['five']['a'] = 'c5a';
I want to have an array of the strings, like this:
array (
0 => 'one',
1 => 'b2',
2 => 'c23',
3 => 'c24',
4 => 'c5a',
)
Here is a recursive function I made. It seems to work. But I'm not sure that I'm doing it right, as far as declaring the static, and when to unset the static var (in case I want to use the function again, I dont want that old static array)
function lastthinggetter($ra){
static $out;
foreach($ra as $r){
if(is_array($r))
lastthinggetter($r);
else
$out[] = $r;
}
return $out;
}
How do I make sure each time I call the function, the $out var is fresh, every time? Is there a better way of doing this?
Maybe check if we're in recursion?
function lastthinggetter($ra, $recurse=false){
static $out;
foreach($ra as $r){
if(is_array($r))
lastthinggetter($r, true);
else
$out[] = $r;
}
$tmp = $out;
if(!$recurse)
unset($out);
return $tmp;
}
Your last version will probably work correctly. However, if you want to get rid of the static variable you could also do it like this:
function getleaves($ra) {
$out=array();
foreach($ra as $r) {
if(is_array($r)) {
$out=array_merge($out,getleaves($r));
}
else {
$out[] = $r;
}
}
return $out;
}
The key here is, that you actually return the so far found values at the end of your function but so far you have not 'picked them up' in the calling part of your script. This version works without any static variables.
I'll simply use array_walk_recursive over here instead like as
array_walk_recursive($ra, function($v)use(&$result) {
$result[] = $v;
});
Demo

Passing object method to array_map() [duplicate]

This question already has answers here:
How to use class methods as callbacks
(5 answers)
Closed 3 months ago.
class theClass{
function doSomeWork($var){
return ($var + 2);
}
public $func = "doSomeWork";
function theFunc($min, $max){
return (array_map(WHAT_TO_WRITE_HERE, range($min, $max)));
}
}
$theClass = new theClass;
print_r(call_user_func_array(array($theClass, "theFunc"), array(1, 5)));
exit;
Can any one tell what i can write at WHAT_TO_WRITE_HERE, so that doSomeWork function get pass as first parameter to array_map. and code work properly.
And give out put as
Array
(
[0] => 3
[1] => 4
[2] => 5
[3] => 6
[4] => 7
)
To use object methods with array_map(), pass an array containing the object and the objects method name. For same-object scope, use $this as normal. Since your method name is defined in your public $func property, you can pass func.
As a side note, the parentheses outside array_map() aren't necessary.
return array_map( [$this, 'func'], range($min, $max));
The following code provides an array of emails from an $users array which contains instances of a class with a getEmail method:
if(count($users) < 1) {
return $users; // empty array
}
return array_map(array($users[0], "getEmail"), $users);
I tried search for solution but it not works, so I created custom small map function that will do the task for 1 variable passed to the function it simple but will act like map
class StyleService {
function check_css_block($str){
$check_end = substr($str,-1) == ';';
$check_sprator = preg_match_all("/:/i", $str) == 1;
$check_sprator1 = preg_match_all("/;/i", $str) == 1;
if ( $check_end && $check_sprator && $check_sprator1){
return $str;
} else {
return false;
}
}
function mymap($function_name, $data){
$result = array();
$current_methods = get_class_methods($this);
if (!in_array($function_name, $current_methods)){
return False;
}
for ($i=0; $i<count($data); $i++){
$function_result = $this->{$function_name}($data[$i]);
array_push($result, $function_result);
}
return $result;
}
function get_advanced_style_data($data)
{
return $this->mymap('check_css_block', $data);
}
}
this way you can call a function name as string $this->{'function_name'}() in php

Categories