how to use variable outside foreach loop - php

How to return $value after loop with its returned data ? I think to create array before loop and equal it to $v to use it after loop but it didn't work.
Any idea on how to solve this problem ?
// create array
$v = array();
// start loop
foreach ($this->json_data->locations as $key => $value) {
if ($value->country_name == $data['city']->country_name)
// return $value with data
return $v = $value ;
}
echo $v->country_name

try this:
$v = array();
foreach ($this->json_data->locations as $key => $value) {
if ($value->country_name == $data['city']->country_name)
{
if(!in_array($value,$v))
{
array_push($v,$value);
}
}
}

try this
$v = array();
$i=0;
// start loop
foreach ($this->json_data->locations as $key => $value) {
if ($value->country_name == $data['city']->country_name)
// return $value with data
$i++;
$v[$i] = $value ;
}
//print $v
print_r($v)

If like using 'return' try this.
$v = iLikeUsingReturn($this,$data);
function iLikeUsingReturn($t,$d){
foreach ($t->json_data->locations as $key => $value) {
if ($value->country_name == $d['city']->country_name)
return $value ;
}
return array();
}

I think the following code will helps you.
// create array
$v = array();
// start loop
foreach ($this->json_data->locations as $key => $value) {
if ($value->country_name == $data['city']->country_name)
// return $value with data
array_push($v, $value);
}
return $v;

Related

PHP How to merge array element with next while maintaining order?

$array = ['coke.','fanta.','chocolate.'];
foreach ($array as $key => $value) {
if (strlen($value)<6) {
$new[] = $value." ".$array[$key+1];
} else {
$new[] = $value;
}
}
This code doesn't have the desired effect, in fact it doesn't work at all. What I want to do is if an array element has string length less than 5, join it with the next element. So in this case the array should turn into this:
$array = ['coke. fanta.','chocolate.'];
$array = ['coke.','fanta.','chocolate.', 'candy'];
$new = [];
reset($array); // ensure internal pointer is at start
do{
$val = current($array); // capture current value
if(strlen($val)>=6):
$new[] = $val; // long string; add to $new
// short string. Concatenate with next value
// (note this moves array pointer forward)
else:
$nextVal = next($array) ? : '';
$new[] = trim($val . ' ' . $nextVal);
endif;
}while(next($array));
print_r($new); // what you want
Live demo
With array_reduce:
$array = ['coke.', 'fanta.', 'chocolate.', 'a.', 'b.', 'c.', 'd.'];
$result = array_reduce($array, function($c, $i) {
if ( strlen(end($c)) < 6 )
$c[key($c)] .= empty(current($c)) ? $i : " $i";
else
$c[] = $i;
return $c;
}, ['']);
print_r($result);
demo
<pre>
$array = ['coke.','fanta.','chocolate.'];
print_r($array);
echo "<pre>";
$next_merge = "";
foreach ($array as $key => $value) {
if($next_merge == $value){
continue;
}
if (strlen($value)<6) {
$new[] = $value." ".$array[$key+1];
$next_merge = $array[$key+1];
} else {
$new[] = $value;
}
}
print_r($new);
</pre>
Updated Code after adding pop after chocolate.
<pre>
$array = ['coke.','fanta.','chocolate.','pop'];
print_r($array);
echo "<br>";
$next_merge = "";
foreach ($array as $key => $value) {
if($next_merge == $value){
continue;
}
if (strlen($value)<6 && !empty($array[$key+1])) {
$new[] = $value." ".$array[$key+1];
$next_merge = $array[$key+1];
} else {
$new[] = $value;
}
}
print_r($new);
<pre>
You need to skip the iteration for the values that you have already added.
$array = ['coke.', 'fanta.', 'chocolate.'];
$cont = false;
foreach ($array as $key => $value) {
if ($cont) {
$cont = false;
continue;
}
if (strlen($value) < 6 && isset($array[$key+1])) {
$new[] = $value.' '.$array[$key+1];
$cont = true;
}
else {
$new[] = $value;
}
}
print_r($new);

Unable to print array outside foreach loop

$val = array();
foreach ($value as $key) {
$nested = $this->Mdl_mymodel->arr($key);
if($nested != NULL) {
$n = 0;
foreach ($nested as $nest) {
$n++;
$val[$n] = $nest->num;
}
}
else {
$val = '';
}
print_r($val);
}
print_r($val);
Here $val inside the loop is printed but outside it is empty. I think i am missing something. Please help!
Note: I am using codeigniter.
$val = array();
foreach ($value as $key) {
$nested = $this->Mdl_mymodel->arr();
if($nested != NULL) {
$n = 0;
foreach ($nested as $nest) {
$n++;
$val[$n] = $nest->num;
}
}
else {
// $val = ''; Commented this line because you have already
// initialized $val. If you do not get records,
// it will return as blank array.
}
print_r($val);
}
print_r($val);

PHP: Wildcards on multidimensional key

I have a multidimensional array $array["A"]["B"]["C"]["D"]. The list is longer.
Is there a wildcard that I can use to get ["D"] value in let say ["B"] array?
Something like this, $array["A"]["B"][*]["D"] ?
or $array[*]["B"][*]["D"] ?
Example, I would like to get all prices that were bought on February regardless of the year.
$array[2013][2][23]["ItemName"]["ItemPrice"] .....
If this would work, it would be really wonderful
$array[*][2][*][*]["ItemPrice"]..
any idea?
You could do multiple foreach to loop though every nested array that you want to loop though.
foreach ($array as $a) {
foreach ($a["B"] as $c) {
foreach ($c as $d) {
// Do something with $d
}
}
}
This would be $array[*]["B"][*][*]
Edit: You could combine my suggestion with a while loop.
$innerArray = $array;
while (true) {
foreach ($array as $key => $value) {
if ($key == "D") {
// Do something with this value
} else if (is_array($value)) {
$innerArray = $value;
} else {
break;
}
}
}
Thanks to #Sepehr-Farshid it just crossed my mind that I can use recursive function (Something that I haven't use for quiet a while. So here a example.
$newarray = array();
$tempArray = $oldarray;
$levels[] = 1;
$keys[] = 2;
$levels[] = 4;
$keys[] = "ItemPrice";
$lastLevel =4;
recurArray($tempArray, 0);
function recurArray($array, $level)
{
foreach($array as $key => $value) {
if(array_search($level, $GLOBALS["levels"]) {
$tempKey = array_search($level, $GLOBALS["levels"];
if($key == $GLOBALS["keys"][$tempKey] {
if($level == $GLOBALS["lastLevel"]) $GLOBALS["newarray"] = $value;
else recurArray($value, $level + 1);
}
else { return; }
}
else { recurArray($value, $level + 1); }
}
}
this might not be the optimum way, but it will work and can be refined. :D

Replacing array value in foreach loop

What am I doing wrong here? It's so simple and I'm overlooking something. I'm trying to replace the value of an array key within a foreach loop:
$arr = array();
$arr['firstimg'] = '123';
$arr['secondimg'] = '456';
$arr['thirdimg'] = '789';
foreach ($arr as $key => $value) {
if ($key == 'secondimg') {
$value = '000';
}
}
print_r($arr);
The array is staying the same.
The variable $value is scoped to the loop. You need to update the value of $arr[$key].
Alternatively you can declare the loop as follows:
foreach ($arr as $key => &$value) {
This makes $value a reference to the original array value (rather than a copy).
Should Be :
foreach ($arr as $key => $value) {
if ($key == 'secondimg') {
$arr['secondimg'] = '000';
}
}
pass by refrence,
$arr = array();
$arr['firstimg'] = '123';
$arr['secondimg'] = '456';
$arr['thirdimg'] = '789';
foreach ($arr as $key => $value) {
if ($key == 'secondimg') {
$value = '000';
}
}
print_r($arr);
to
$arr = array();
$arr['firstimg'] = '123';
$arr['secondimg'] = '456';
$arr['thirdimg'] = '789';
foreach ($arr as $key => &$value) {
if ($key == 'secondimg') {
$value = '000';
}
}
print_r($arr);

Comparing in_array values

I have a array of val which has dynamic strings with underscores. Plus I have a variable $key which contains an integer. I need to match $key with each $val (values before underscore).
I did the following way:
<?php
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
if(in_array($key, $val)) {
echo 'Yes';
}
else
{
echo 'No';
}
?>
Though this code works fine, I want to know if its a correct way or suggest some better alternative.
use this function for regex match from php.net
function in_array_match($regex, $array) {
if (!is_array($array))
trigger_error('Argument 2 must be array');
foreach ($array as $v) {
$match = preg_match($regex, $v);
if ($match === 1) {
return true;
}
}
return false;
}
and then change your code to use this function like this:
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
if(in_array_match($key."_*", $val)) {
echo 'Yes';
}
else
{
echo 'No';
}
This should work :
foreach( $val as $v )
{
if( strpos( $v , $key .'_' ) === true )
{
echo 'yes';
}
else {
echo 'no';
}
}
you can use this
function arraySearch($find_me,$array){
$array2 =array();
foreach ($array as $value) {
$val = explode('_',$value);
$array2[] =$val[0];
}
$Key = array_search($find_me, $array2);
$Zero = in_array($find_me, $array2);
if($Key == NULL && !$Zero){
return false;
}
return $Key;
}
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
$inarray = false;
foreach($val as $v){
$arr = explode("_", $val);
$inarray = $inarray || $arr[0] == $key
}
echo $inarray?"Yes":"No";
The given format is quite unpractically.
$array2 = array_reduce ($array, function (array $result, $item) {
list($key, $value) = explode('_', $item);
$result[$key] = $value;
return $result;
}, array());
Now you can the existence of your key just with isset($array2[$myKey]);. I assume you will find this format later in your execution useful too.

Categories