can somone explain me how this code works
<?php
function append($initial)
{
$result=func_get_arg(0);
foreach(func_get_arg()as $key=>value){
if($key>=1)
{
$result .=' '.$value;
}
}
return $result;
echo append('Alex,'James','Garrett');
?>
why do we have a 0 at the func_get_arg(0), and this is a loop there are 0,1,2 shouldn't it only post Alex, James?
and what is the (as) does the func_get_arg() as $key => value. give the array the names to the value ?
this is basic but a bit messy!
That's how it works:
<?php
function append($initial)
{
// Get the first argument - func_get_arg gets any argument of the function
$result=func_get_arg(0);
// Get the remaining arguments and concat them in a string
foreach(func_get_args() as $key=>value) {
// Ignore the first (0) argument, that is already in the string
if($key>=1)
{
$result .=' '.$value;
}
}
// Return it
return $result;
}
// Call the function
echo append('Alex,'James','Garrett');
?>
This function will do the same that:
echo implode(' ', array('Alex', 'James', 'Garrett'));
before you used the foreach{} loop. You have returned 'Alex' which is at position 0.
$result=func_get_arg(0);
foreach(){
}
return $result; //It returns Alex
//foreach() loop
foreach(func_get_arg()as $key=>value){
/*Its looping and only printing after
the key gets to 1 and then the loop goes to 2.Eg: $result[$key]=> $value; */
if($key>=1)
{
$result .=' '.$value;
}
}
Related
I need to turn each end-point in a multi-dimensional array (of any dimension) into a row containing the all the descendant nodes using PHP. In other words, I want to resolve each complete branch in the array. I am not sure how to state this more clearly, so maybe the best way is to give an example.
If I start with an array like:
$arr = array(
'A'=>array(
'a'=>array(
'i'=>1,
'j'=>2),
'b'=>3
),
'B'=>array(
'a'=>array(
'm'=>4,
'n'=>5),
'b'=>6
)
);
There are 6 end points, namely the numbers 1 to 6, in the array and I would like to generate the 6 rows as:
A,a,i,1
A,a,j,2
A,b,2
B,a,m,3
B,a,n,4
B,b,2
Each row contains full path of descendants to the end-point. As the array can have any number of dimensions, this suggested a recursive PHP function and I tried:
function array2Rows($arr, $str='', $out='') {
if (is_array($arr)) {
foreach ($arr as $att => $arr1) {
$str .= ((strlen($str)? ',': '')) . $att;
$out = array2Rows($arr1, $str, $out);
}
echo '<hr />';
} else {
$str .= ((strlen($str)? ',': '')) . $arr;
$out .= ((strlen($out)? '<br />': '')) . $str;
}
return $out;
}
The function was called as follows:
echo '<p>'.array2Rows($arr, '', '').'</p>';
The output from this function is:
A,a,i,1
A,a,i,j,2
A,a,b,3
A,B,a,m,4
A,B,a,m,n,5
A,B,a,b,6
Which apart from the first value is incorrect because values on some of the nodes are repeated. I have tried a number of variations of the recursive function and this is the closest I can get.
I will welcome any suggestions for how I can get a solution to this problem and apologize if the statement of the problem is not very clear.
You were so close with your function... I took your function and modified is slightly as follows:
function array2Rows($arr, $str='', $csv='') {
$tmp = $str;
if (is_array($arr)) {
foreach ($arr as $att => $arr1) {
$tmp = $str . ((strlen($str)? ', ': '')) . $att;
$csv = array2Rows($arr1, $tmp, $csv);
}
} else {
$tmp .= ((strlen($str)? ', ': '')) . $arr;
$csv .= ((strlen($csv)? '<br />': '')) . $tmp;
}
return $csv;
}
The only difference is the introduction of a temporary variable $tmp to ensure that you don't change the $str value before the recursion function is run each time.
The output from your function becomes:
This is a nice function, I can think of a few applications for it.
The reason that you are repeating the second to last value is that in your loop you you are appending the key before running the function on the next array. Something like this would work better:
function array2Rows($arr, &$out=[], $row = []) {
if (is_array($arr)) {
foreach ($arr as $key => $newArray) {
if (is_array($newArray)) {
$row[] = $key; //If the current value is an array, add its key to the current row
array2Rows($newArray, $out, $row); //process the new value
} else { //The current value is not an array
$out[] = implode(',',array_merge($row,[$key,$newArray])); //Add the current key and value to the row and write to the output
}
}
}
return $out;
}
This is lightly optimized and utilizes a reference to hold the full output. I've also changed this to use and return an array rather than strings. I find both of those changes to make the function more readable.
If you wanted this to return a string formatted similarly to the one that you have in your function, replace the last line with
return implode('<br>', $out);
Alternatively, you could do that when calling, which would be what I would call "best practice" for something like this; e.g.
$result = array2Rows($arr);
echo implode('<br>', $result);
Note, since this uses a reference for the output, this also works:
array2Rows($arr, $result);
echo implode('<br>', $result);
I need one help. I need to check that string is present inside array or not and also it should search letter wise using PHP. I am explaining my code below.
$resultArr=array("9937229853","9937229856","9937229875");
$searchValue="+919937229853";
Here I need to check that some of the value from $searchValue is present inside in array or not. I am doing like below but its not giving me the proper result.
$searchValue="+919937229853";
$resultArr=array("9937229853","9937229856","9937229875");
if(!in_array($searchValue, $resultArr))
{
$flag=1;
}else{
$flag=0;
}
echo $flag;
As per my requirement here result should print 1 because some value from $searchValue also present in that array but the echo result is coming 0.Please help me.
$searchValue="+919937229853";
$resultArr=array("9937229853","9937229856","9937229875");
foreach($resultArr as $value)
{
if(strpos($value,$searchValue) || strpos($searchValue,$value) || $searchValue==$value)
{
$flag = 1;
break;
}
else
$flag=0;
}
echo $flag;
I think this will do what you are looking for. in_array() method search string in array but for the exact string. strpos can search substring in long string and return the offset number or the index of substring in the long string.
you can try code like below.
if(!in_array(substr($searchValue,-10), $resultArr))
$searchValue="+919937229853";
$searchValue = str_replace("+91","",$searchValue);
$resultArr=array("9937229853","9937229856","9937229875");
if(in_array($searchValue, $resultArr))
{
$flag=1;
}else{
$flag=0;
}
echo $flag;
User str_replace function replace first three charater from string
$flag=0;
for($i=0;$i<strcmp($searchValue);$i++){
for($j=0;$j<strcmp($searchValue);$j++){
$part=substr($searchValue,$i,$j)
array_filter($resultArr, function($el) use ($part) {
if ( strpos($el, $part) !== false ){
$flag=1;
}
});
}
}
The function below will return true if either
your $searchValue is in the array (in_array), or
if any item of the array is a substring of $searchValue
in other words: If part of $searchValue is in the array.
This is the code and how you call it:
function search($needle, $haystack) {
// is $needle contained in the array as it is?
if (in_array($needle, $haystack))
return true;
// Is any part of $needle part of the array?
foreach ($haystack as $value) {
if (strpos($needle, $value) !== FALSE)
return true;
}
return false;
}
$resultArr = array("9937229853", "9937229856", "9937229875");
$searchValue = "+919937229853";
$result = search($searchValue, $resultArr);
var_dump($result);
I have this array of objects:
$table=[{"count":"2","id_f":"2255"},{"count":"6","id_f":"5886"}];
I want to get the value of id_f of each object and check if this value exist in another array ,I tried with this but it gives me the wrong result:
foreach($table as $t){
if (in_array($t[$id_f],$array){
//dosomething}
}else{
//do something else
}
}
I also tried with this:
foreach($table as $t){
if (in_array($t->$id_f,$array){
//dosomething}
}else{
//do something else
}
}
I can't get the right result , I will appreciate any help.
Another approach without foreach loop:
<?php
$table=json_decode('[{"count":"2","id_f":"2255"},{"count":"6","id_f":"5886"}]');
$data = [10, 20, 2255];
array_walk($table, function($obj) use (&$data) {
if (in_array($obj->id_f, $data)) {
echo "+";
} else {
echo "-";
}
});
The output obviously is:
+-
You dont show a json_decode() anywhere in your code, thats the first thing to do with a JSON String, to decode it into a PHP data structure. In this case an array of objects.
$other_array = array('2255', '9999');
$table='[{"count":"2","id_f":"2255"},{"count":"6","id_f":"5886"}]';
$array = json_decode($table);
foreach ( $array as $obj ) {
if (in_array($obj->id_f, $other_array)) {
echo 'Found one ' . $obj->id_f . PHP_EOL;
} else {
echo 'No match for ' . $obj->id_f . PHP_EOL;
}
}
Results
Found one 2255
No match for 5886
There's no need for the dollar sign before your Object property name (actually, it won't work, except of course if $id_f is a real variable which has for value 'id_f', but somehow I doubt it) :
foreach ($table as $t) {
if (in_array($t->id_f, $array){
// do something
} else {
// do something else
}
}
it can be done like this:
to define the object array you can define like below with json string approach. or to define object is like this $table = new stdClass();
<?php
$table='[{"count":"2","id_f":"2255"},{"count":"6","id_f":"5886"}]';
$obj = json_decode($table);
$array=array("2555","2255");
foreach($obj as $t){
if (in_array($t->id_f,$array)){
//dosomething
}else{
//do something else
}
}
?>
I am having trouble in returning all rows from while loop. When checking with print_r($item) it's returning all rows but when I user return in while loop it is only returning first row. I think that is because it is return the loop at the first time.
So how can I return all rows.. here is what I am trying
while($item = db_assoc($query)){
return '<p>'.$item['title'].'</p>';
}
The while loop is within the class method and I have to return the value so can't use echo
Thanks a lot....
Like you say, you're returning after the first row. Try the following:
$output = '';
while ($item = db_assoc($query)) {
$output .= "<p>{$item['title']}</p>";
}
return $output;
try to Create New Array Or Create format for you want inside the While-loop
And Return it..
"return" it stops execution loop.
while ($item = db_assoc($query)) {
$output .= "<p>{$item['title']}</p>";
}
return $output;
You should use
while($item = mysql_fetch_array($runsql)){
$data[]=$item['first_name'];
}
return $data;
it is because when you write return in loop it return with first value,
but in print_r it shows all record . so we have to create an array of required field and then return it
Hope it will help you.
Try this.
while($item = mysql_fetch_array($runsql)){
$data.=$item['first_name']."<br/>";
}
return $data;
Return will simply get out of the loop that's why it prints only the first row. If you want to return it all, save them in a string and after the while loop just return that string.
The return statement is causing it to break the execution of the loop.
Try this instead:
while($item = db_assoc($query)){
$titles[] = '<p>'.$item['title'].'</p>';
}
And to access the titles, you can simply use a foreach loop:
foreach($titles as $title){
echo "<p> $title </p";
}
I want to apply a function to each element/prop of an object but it seems array_walk_recursive() does not work on object. i.e:
if( $re = $con->query("SELECT id, created_date, contents FROM " .
POST_DATA . " WHERE type = 'news' ORDER BY ".
"created_date DESC LIMIT $amount") ) {
if( $re->num_rows != 0 ) {
while( $ob = $re->fetch_object() ) {
$ob = array_walk_recursive( $ob, "_output" );
print_r($ob);
die();
}
}
}
would simply return '1'.
How might I resolve this?
It's actually returning a value of True for array_walk_recursive. If you look at the function's documentation, you'll see that what this method is doing is calling the function _output for each item and key in the object.
You should also have some code that looks similar to this, I would imagine, to get it to work correctly:
function _output($data, $key) {
echo "For the key $key, I got the data: ";
print_r($data);
}
Where _output is called because that is the stringified name that you gave in the array_walk_recursive function. That should print your values to the screen.
Edit:
It seems that I'm not actually answering what you were originally wanting to do, though. If you're wanting to apply a function to every element of an array, I would suggest that you look at array_map. You can use array_map like this:
function double($item) {
return 2 * $item;
}
array_map('double', $item);
Ultimately, if the recursion is something that you desire, you could probably do something like this:
function callback($key, $value) {
// do some stuff
}
function array_map_recursive($callback, $array) {
$new_array = array()
foreach($array as $key => $value) {
if (is_array($value)) {
$new_array[$key] = array_map_recursive($callback, $value);
} else {
$new_array[$key] = call_user_func($callback, $key, $value);
}
}
return $new_array;
}
array_map_recursive('callback', $obj);
That would return another array like $obj, but with whatever the callback was supposed to do.