Scoping Issue with PHP Arrays - php

I'm trying to solve this problem where I have a unique array of values within a specific range. Take this scenario: Generate a fixed value array (90) with unique entries. If you find a duplicate, remove, reindex, and fill the void. I'm running into the problem that conditional statements do not allow you to interact with an array outside of it's scope. I'm aware of array_unique but it doesn't refill those gaps, just makes them. How do I refill those gaps?
EDIT: This was a noobish question about scoping. A simple while loop demonstrated that if conditional statements can modify variables outside of it's scope.
?>

Not sure if this will help but you can always reiterate over the array once the duplicateds have been removed and reindex it if that is what you mean?

Making sure I understand this - you don't care for the array key elements?
You could still use array_unique();
// $array(); is already defined with elements in it
$temp_array = array_unique($array);
if ( !empty ( $temp_array ) ) {
unset($array);
$array = array();
foreach ( $temp_array as $t ) {
array_push($array, $t);
}
}
You'd probably want to put a clause in there stopping it if it goes over 90 elements.

Related

PHP saving a value of array outside of foreach [duplicate]

This question already has answers here:
How to modify an array's values by a foreach loop?
(2 answers)
Closed 4 months ago.
I was wondering if it is possible to edit the current object that's being handled within a foreach loop
I'm working with an array of objects $questions and I want to go through and look for the answers associated with that question object in my db. So for each question go fetch the answer objects and update the current $question inside my foreach loop so I can output/process elsewhere.
foreach($questions as $question){
$question['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
There are 2 ways of doing this
foreach($questions as $key => $question){
$questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
This way you save the key, so you can update it again in the main $questions variable
or
foreach($questions as &$question){
Adding the & will keep the $questions updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)
Per the PHP foreach documentation:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
Surely using array_map and if using a container implementing ArrayAccess to derive objects is just a smarter, semantic way to go about this?
Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.
For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN() clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.
<?php
$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);
vs
<?php
$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
$arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);
If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr you could always $arr = array_map and be explicit.

php change specific value of nested array item [duplicate]

This question already has answers here:
How to modify an array's values by a foreach loop?
(2 answers)
Closed 4 months ago.
I was wondering if it is possible to edit the current object that's being handled within a foreach loop
I'm working with an array of objects $questions and I want to go through and look for the answers associated with that question object in my db. So for each question go fetch the answer objects and update the current $question inside my foreach loop so I can output/process elsewhere.
foreach($questions as $question){
$question['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
There are 2 ways of doing this
foreach($questions as $key => $question){
$questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
This way you save the key, so you can update it again in the main $questions variable
or
foreach($questions as &$question){
Adding the & will keep the $questions updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)
Per the PHP foreach documentation:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
Surely using array_map and if using a container implementing ArrayAccess to derive objects is just a smarter, semantic way to go about this?
Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.
For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN() clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.
<?php
$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);
vs
<?php
$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
$arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);
If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr you could always $arr = array_map and be explicit.

Creating an associative array from an array, based on the array - PHP

I have a unique issue that I have never heard of this being possible to do before:
So essentially I have a function that takes in a an array of arguments such as:
function someFunction(array $arguments){}
and gives me an array back as such:
array('option1', 'option2', 'options3', ...);
I then need to take that array and loop through it creating an associative array such as:
array('option1' => call_come_method('option1'), .... );
heres the kicker, you will never know how many arguments a user passes into the function, yet each one needs to created into a key=>value arrangement as seen above.
Now i did some research and I was told the $argv command in php, how ever where I am stumped is how to implement it in this case.
So if any one can give me any pointers I would be appreciative.
This is a lot easier than you think. First use array_flip to switch the array's keys and values.
$newArray = array_flip($arguments);
Then loop though it and call the method:
foreach($newArray as $key=>&$val){
$val = call_come_method($key);
}
The &, makes it a reference, so the array value is updated.
DEMO: http://codepad.org/giL1KPA3
UPDATE: You don't even need array_flip, you just need a for loop.
$newArray = array();
foreach($arguments as $val){
$newArray[$val] = call_come_method($val);
}
DEMO: http://codepad.org/AQ1gWrou
you will never know how many arguments a user passes into the function
FYI, you get to know it with func_get_args().
This way you don't need to provide your function with an $arguments parameter, but you just leave it empty.

Modify array values in foreach loop [duplicate]

This question already has answers here:
How to modify an array's values by a foreach loop?
(2 answers)
Closed 4 months ago.
I was wondering if it is possible to edit the current object that's being handled within a foreach loop
I'm working with an array of objects $questions and I want to go through and look for the answers associated with that question object in my db. So for each question go fetch the answer objects and update the current $question inside my foreach loop so I can output/process elsewhere.
foreach($questions as $question){
$question['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
There are 2 ways of doing this
foreach($questions as $key => $question){
$questions[$key]['answers'] = $answers_model->get_answers_by_question_id($question['question_id']);
}
This way you save the key, so you can update it again in the main $questions variable
or
foreach($questions as &$question){
Adding the & will keep the $questions updated. But I would say the first one is recommended even though this is shorter (see comment by Paystey)
Per the PHP foreach documentation:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
Surely using array_map and if using a container implementing ArrayAccess to derive objects is just a smarter, semantic way to go about this?
Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.
For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN() clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.
<?php
$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);
vs
<?php
$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
$arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);
If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr you could always $arr = array_map and be explicit.

Problem with array values

I am having a problem where a routine (that I cannot modify) is returning me either a 3 nested array -or- a 2 nested array. The key values are never the same, however, I'd like to normalize the nesting so that I can make the 2 nested array 3 levels deep every time to avoid "Notice: Undefined index:" errors. Or if possible, have a routine to count the number of levels deep the array is so I can code accordingly.
You can use isset() to determine if a particular level is present in the array. If not, add it.
function get_depth($arr) {
foreach ( $arr as $arr2 ) {
if ( is_array($arr2) ) {
return 1+get_depth($arr2);
}
break;
}
return 1;
}
Well, this answer is really going to depend on what you're doing. Why not simply check to see if the nested array exists?
if (isset($val[3][2])) {
....
}

Categories