how to iterate front and back in php foreach array? - php

I want to achieve this
foreach($spacecount as $x => $x_value) {
if($spacecount[$x+1] < $spacecount[$x+2] ) {
echo $spacecount[$x];
}
}
like we can do it in for loop, but i also want to use its key when needed. how can I perform it ?
The array looks like
Array ( [ Tables] => 5
[Home] => 0
[ Wallet] => 5
[Designer] => 0
)
it contains whitespaces in the key text

If there's no guarantee that your array is numerically indexed, you can do this:
$keys = array_keys($spacecount);
$values = array_values($spacecount);
for ($i = 0;$i < count($spacecount)-2;$i++) {
//If you need the key you can use $keys[$i]
if ($values[$i+1] < $values[$i+2]) {
echo $values[$i+1];
}
}

Related

How do I replace an element in an array if its key matches the key of another array?

I have two txt files with the same length (10 lines in each). One file has IDs, and the other has a "rating" (0, 1, 2, etc) that is associated with each ID. For example:
txt 1 | txt 2
123 | 1
234 | 2
etc.
I want to replace the rating when I provide an ID.
What I did was search the key associated with the provided ID and when it matches the key in the ratings array I replace the corresponding value in the ratings array.
So the idea is find key for '123' in ids (key=0) and replace the rating value with key=0 (in this case 1) for another value.
I have the following in a function:
public function updateRating($disease, $id, $rating){
$filename = $disease.".txt";
$filename_2 = $disease."Ratings.txt";
$ids = file($filename);
$ratings = file($filename_2);
$index_ids = array_keys($ids, $id."\n");
$index_ratings = array_keys($ratings);
$size = count($ids);
for($i=0; $i<$size; $i++){
if($index_ratings[$i] == $index_ids){
$ratings = str_replace($ratings[$i], $rating."\n", $ratings);
}
}
$ratings_n = implode("", $ratings);
file_put_contents($filename_2, $ratings_n);
return array("debug2" => $index_ids, "debug3" => $index_ratings, "debug4" => $ratings);
The index_ids (the key for the provided ID) is being returned correctly, but the array for the ratings ($ratings) is returned as if nothing was replaced. What is wrong in this code and how can I correct it to do what I want it to do?
Use array_search() in your function to get the key:
https://paiza.io/projects/zdg_xzGwV8KfgOqkzeCgjA
function replaceValue($value, $arr1, &$arr2){
$key = array_search($value, $arr1);
if($key === false){
return false;
}else{
$arr2[$key] = $value;
return true;
}
}
if(replaceValue("baz", $arr1, $arr2)){
print_r($arr2);
}else{
echo "no match found";
}
Result:
Array
(
[x] => bizz
[y] => bazz
[c] => baz
)
You can follow this kind of steps to achieve the result
<?php
$arr1 = [0 => '123', 1 => '234'];
$arr2 = [0 => 'a', 1 => 'b'];
for ($i=0; $i < sizeof($arr1) ; $i++) {
for ($i=0; $i < sizeof($arr1) ; $i++) {
if ($arr1[$i] == '123') {
$arr2[$i] = 'abc';
}
}
}
echo'<pre>';
print_r($arr2);
echo '<pre>';
?>
Output
Array
(
[0] => abc
[1] => b
)

How to get a multidimensional array's name?

I'm trying to get the name of an array once I have found a specific value.
Specifically I'm looking to get the highest and lowest values within my array for a certain key, once I have those values I then need to get the name of the array holding those values.
My array looks like this -
Array
(
[123456] => Array
(
[value1] => 0.524
[value2] => 0.898
[value3] => -6.543
)
[246810] => Array
(
[value1] => 0.579
[value2] => 0.989
[value3] => -5.035
)
I have gotten the max value using this code -
max(array_column($statsArr, 'value1'));
This, correctly, gives me the value "0.579". I now need to get the value of the array holding this information so in this case I also want to get the value "246810". I don't know how to do this though, any help would be appreciated!
Iterate over your array with a simple foreach and save required key:
$max = 0;
$founded_key = false;
foreach ($array as $key => $value) {
if ($max < $value['value1']) {
$max = $value['value1'];
$founded_key = $key;
}
}
echo $founded_key, ' - ', $max;
For these kinds of problems I like using array_reduce. max is itself an array reduce operation which takes an array and returns a single value, PHP just offers it out of the box as convenience since it's a very common operation.
Here's an example code:
$array = array(
123456 => array(
'value1' => 0.524,
'value2' => 0.898,
'value3' => -6.543
),
246810 => array(
'value1' => 0.579,
'value2' => 0.989,
'value3' => -5.035
)
);
$maxKey = array_reduce(array_keys($array), function ($carry, $key) use ($array) {
if ($carry === null) {
return $key;
}
return $array[$key]['value1'] > $array[$carry]['value1'] ? $key : $carry;
}, null);
$maxValue = $array[$maxKey]['value1'];
Working example: http://sandbox.onlinephpfunctions.com/code/ecd400ffec91a6436c2fb5ee0410658e22772d4b
function getMax($array, $field) {
$maxValue = null;
$maxKey = null;
foreach($array as $key => $content) {
if (is_null($maxValue) || $content[$field] > $maxValue) {
$maxValue = $content[$field];
$maxKey = $key;
}
}
return [$maxValue, $maxKey];
}
You can search for the maximum value in the array_column.
I first prepare the array_column with correct keys by combining it, then find the max like you do.
Then we can array_search the value.
$value1 = array_combine(array_keys($statsArr), array_column($statsArr, 'value1'));
$max = max($value1);
echo $max . PHP_EOL;
$array = $statsArr[array_search($max, $value1)];
var_dump($array);
https://3v4l.org/Q9gOX
Alternatively you can array_values the $statsArr to make it 0 indexed just like the array_column.
$value1 = array_column($statsArr, 'value1');
$max = max($value1);
echo $max . PHP_EOL;
$array = array_values($statsArr)[array_search($max, $value1)];
var_dump($array);

Re-index numeric nested arrays keys

Here is my array:
$arr = [
1 => [
2 => "something",
3 => "something else"
],
2 => "foo br"
];
I need to restart all keys and start all of them from 0. Based on some researches, I figured out I have to use array_values() function. But it just makes the keys of outer array re-index, See.
How can I apply it on the all keys of array? (even nested ones)
You can use array_values + recursively calling custom function:
function arrayValuesRecursive($array) {
$array = array_values($array);
$countValues = count($array);
for ($i = 0; $i < $countValues; $i++ ) {
$subElement = $array[$i];
if (is_array($subElement)) {
$array[$i] = arrayValuesRecursive($subElement);
}
}
return $array;
}
$restructuredArray = arrayValuesRecursive($array);
You can implement it using recursion like this:
function reIndex($arr) {
$arr = array_values($arr);
foreach ($arr as $k => $v) {
if (is_array($v)) {
$arr[$k] = reIndex($v);
}
}
return $arr;
}
$arr = reIndex($arr);
Hi checkout following code
<?php
$arr = [
1 => [
2 => "something",
3 => "something else"
],
2 => "foo br"
];
$reIndexedArray = array();
foreach($arr as $arrItr){
$reIndexedArray[] = count($arrItr) > 1 ? array_values($arrItr) : $arrItr;
}
print_r($reIndexedArray);
?>
output is
Array
(
[0] => Array
(
[0] => something
[1] => something else
)
[1] => foo br
)

Building an associative array using for loop in php

I am trying to create an associative array using php. My desired output is
Array
(
[key] => fl_0_sq
),
Array
(
[key] => fl_1_sq
)
The code is
$max_val = 2;
for($i=0; $i<$max_val; $i++)
{
$flr_arr .= "array('key' => 'fl_".$i."_sq'),";
}
print_r($flr_arr);
Output is
array('key' => 'fl_0_sq'),array('key' => 'fl_1_sq'),
Now the issue is that it has become a string instead of an array. Is it at all possible to create a array structure like the desired output. Any help is highly appreciated.
You could do this:
<?php
$flr_arr = [];
$max_val = 2;
for ($i = 0; $i < $max_val; $i++) {
$flr_arr[][key] = 'fl_' . $i . '_sq';
}
$output = "<pre>";
foreach ($flr_arr as $i => $flr_arr_item) {
$output .= print_r($flr_arr_item, true);
if($i < count($flr_arr)-1){
$output = substr($output, 0, -1) . ",\n";
}
}
$output .= "</pre>";
echo $output;
The output:
Array
(
[key] => fl_0_sq
),
Array
(
[key] => fl_1_sq
)
I'm not exactly sure what you want to do, but your output could be done by this:
$max_val = 2;
for($i=0; $i<$max_val; $i++)
{
$flr_arr = [];
$flr_arr['key'] = 'fl_".$i."_sq';
print_r($flr_arr);
}
You're declaring a string and concatenating it. You want to add elements to an array. You also can't create multiple arrays with the same name. What you can do, though is a 2D array:
$flr_arr[] = array("key"=>"fl_$i_sq");
Note the lack of quotes around array(). The "[]" syntax adds a new element to the end of the array. The output would be -
array(array('key' => 'fl_0_sq'),array('key' => 'fl_1_sq'))

Combine post values and remove empty

I have two sets of arrays coming from $_POST. Keys for both will be numeric and the count will be the same, since they come in pairs as names and numbers:
$_POST[names]
(
[0] => First
[1] => Second
[2] =>
[3] => Fourth
)
$_POST[numbers]
(
[0] => 10
[1] =>
[2] => 3
[3] => 3
)
Now I need to combine those two, but remove each entry where either values are missing.
The result should be something like:
$finalArray
(
[First] => 10
[Fourth] => 3
)
Post data is dynamically created so there might be different values missing based on user input.
I tried doing something like:
if (array_key_exists('names', $_POST)) {
$names = array_filter($_POST['names']);
$numbers = array_filter($_POST['numbers']);
if($names and $numbers) {
$final = array_combine($names, $numbers);
}
}
But I can't seem to filter it correctly, since its giving me an error:
Warning: array_combine(): Both parameters should have an equal number of elements
How about using array_filter with ARRAY_FILTER_USE_BOTH flag on?
<?php
$array1 = [
0 => "First",
1 => "Second",
2 => "",
3 => "Fourth",
];
$array2 = [
0 => 10,
1 => "",
2 => 3,
3 => 3,
];
var_dump(array_filter(array_combine($array1, $array2), function($value, $key) {
return $key == "" || $value == "" ? false : $value;
}, ARRAY_FILTER_USE_BOTH ));
/*
Output:
array(2) {
["First"]=>
int(10)
["Fourth"]=>
int(3)
}
*/
Here's a fun way:
$result = array_flip(array_flip(array_filter(array_combine($_POST['names'],
$_POST['numbers']))));
// create array using $_POST['names'] as keys and $_POST['numbers'] as values
$result = array_combine($_POST['names'], $_POST['numbers']);
// remove entries that have empty values
$result = array_filter($result);
// remove entry with empty key
unset($result[null]);
print_r($result);
If both arrays will have the same count, and the keys will always be numeric, you could do the following:
$total = count($_POST['names']);
$final = array();
for ($i = 0; $i < $total; $i++) {
if (trim($_POST['names'][$i]) != '' && trim($_POST['numbers'][$i]) != '') {
$final[$_POST['names'][$i]] = $_POST['numbers'][$i];
}
}
Or if you prefer to use a foreach instead of for
$final = array();
foreach ($_POST['names'] as $key => $value) {
if (trim($value) != '' && trim($_POST['numbers'][$key]) != '') {
$final[$value] = $_POST['numbers'][$key];
}
}
Takeing your previous information into account:
both keys will be numeric and the count will be the same, since they come in pairs as names and numbers
$myNewArray = array();
$count = 0;
foreach ($_POST['names'] as $bufferArray)
{
if (($bufferArray[$count]!=NULL)&&($_POST['numbers][$count]!=NULL))
{
array_push($myNewArray, array($bufferArray[$count] => $_POST['numbers][$count]);
}
$count++;
}
Let me know if that helps! :)
Note: I made some edits to the code.
Also, my previous code checks if the empty array spaces are NULL. If you want to check if they are either NULL or "" (empty), then replace the line of code with:
if (($bufferArray[$count]!=NULL)&&($_POST['numbers][$count]!=NULL)&&($bufferArray[$count]!="")&&($_POST['numbers][$count]!=""))
{...}

Categories