Can someone help me figure out why I'm getting a syntax error with this function:
function removeFromArray(&$array, $key){
foreach($array as $j=>$i){
if($i == $key){
$array = array_values(unset($array[$j])); //error on this line says expected ;
return true;
break;
}
}
}
Any help most appreciated!
Jonesy
Remove array_values. It seems you just want to remove one value and unset is already doing the job:
function removeFromArray(&$array, $key){
foreach($array as $j=>$i){
if($i == $key){
unset($array[$j]);
return true;
}
}
}
More about unset.
Demo
Side note:
The code after a return is not executed anymore, so break is unnecessary.
$key is a misleading variable name here. Better would be $value.
Update: If you want to reindex the values of the array (in case you have a numeric array), you have to do it in two steps (as unset does not return a value):
unset($array[$j]);
$array = array_values($array);
Demo
You're trying to use the unset function inside array_values? What exactly are you expecting to happen here?
You should be able to just use:
unset($array[$j]);
As you've passed the array in by reference, this should be sufficient to remove it. No need to play with array values.
The problem is the unset. array_values expect an array as parameter, but unset does not have any return value.
I see what you're trying to do, I suggest you use this instead:
function removeFromArray(&$array, $key){
foreach($array as $j=>$i){
if($i == $key){
unset($array[$j]);
}
}
}
You don't actually need to return anything. unset is a void function.
Unset doesn't return anything:
void unset ( mixed $var [, mixed $var [, mixed $... ]] )
Related
Im looking for a way to remove empty elements from an array.
Im aware of array_filter() which removes all empty values.
The thing is that i consider a string containing nothing but spaces, tabs and newlines also to be empty.
So what is best used in this case?
Use trim() in callback for array_filter:
$array = array_filter($array, function ($v) { return (bool)trim($v); });
Or shorter version (with implicit type-casting):
$array = array_filter($array, 'trim');
php empty()
bool empty ( mixed $var )
Determine whether a variable is considered to be empty. A variable is
considered empty if it does not exist or if its value equals FALSE.
empty() does not generate a warning if the variable does not exist.
Something like should do:
foreach($array as $key => $stuff)
{
if(empty(stuff))
{
unset($array[$key]);
}
}
$array = array_values($array );// to reinstate the numerical indexes.
I know this may be late to answer but it is for those who may have interest in other ways to solve this. It is my own way of doing it.
function my_array_filter($my_array)
{
$final_array = array();
foreach ( $my_array as $my_arr )
{
//check if array element is not empty
if (!empty($my_arr)) $final_array[] = $my_arr;
}
//remove duplicate elements
return array_unique( $final_array );
}
Hope someone finds this useful.
Hi I'm working on a checking a given array for a certain value.
my array looks like
while($row = mysqli_fetch_array($result)){
$positions[] = array( 'pos' => $row['pos'], 'mark' => $row['mark'] );
}
I'm trying to get the info from it with a method like
<?php
if(in_array('1', $positions)){
echo "x";
}
?>
This I know the value '1' is in the array but the x isn't being sent as out put. any suggestions on how to get "1" to be recognized as being in the array?
Edit:
I realize that this is an array inside of an array. is it possible to combine in_array() to say something like:
"is the value '1' inside one of these arrays"
in_array is not recursive. You're checking if 1 is in an array of arrays which doesn't make sense. You'll have to loop over each element and check that way.
$in = false;
foreach ($positions as $pos) {
if (in_array(1, $pos)) {
$in = true;
break;
}
}
in_array only checks the first level. In this case, it only sees a bunch of arrays, no numbers of any kind. Instead, consider looping through the array with foreach, and check if that 1 is where you expect it to be.
That's because $positions is an array of arrays (a multi-dimensional array).
It contains no simple '1'.
Try a foreach-loop instead:
foreach($postions as $value)
if ($value["pos"] == '1')
echo "x ".$value["mark"];
The problem is that 1 isn't actually in the array. It's in one of the array's within the array. You are comparing the value 1 to the value Array which obviously isn't the same.
Something like this should get you started:
foreach ($positions as $position) {
if ($position['pos'] == 1) {
echo "x";
break;
}
}
Your array $positions is recursive, due to the fact that you use $positions[] in your first snippet. in_array is not recursive (see the PHP manual). Therefore, you need a custom function which works with recursive arrays (source):
<?php
function in_arrayr( $needle, $haystack ) {
foreach( $haystack as $v ){
if( $needle == $v )
return true;
elseif( is_array( $v ) )
if( in_arrayr( $needle, $v ) )
return true;
}
return false;
}
?>
Instead of calling in_array() in your script, you should now call in_arrayr().
I have an array that contains the location of a value in a very large multidimensional array. I need to take this location and replace the value at the location with another value. I have found numerous articles about returning the value of a position using such an array of indexes by writing a recursive function. However, this won't work because I can't slice up the large array, I need to replace just that one value.
The location would look something like:
array(1,5,3,4,6);
The code I had to find a value is the following:
function replace_value($indexes, $array, $replacement){
if(count($indexes) > 1)
return replace_value(array_slice($indexes, 1), $array[$indexes[0]], $replacement);
else
return $array[$indexes[0]];
}
}
How would I modify this to instead of recursively cutting down an array until the value is found I can simply modify a part of a large array? Is there a way to build
array(1,5,3,4,6);
Into
$array[1][5][3][4][6];
Thanks
You could modify your function like this:
function replace_value($indexes, &$array, $replacement){
if(count($indexes) > 1) {
return replace_value(array_slice($indexes, 1), $array[$indexes[0]], $replacement);
} else {
return $array[$indexes[0]] = $replacement;
}
}
Make sure your write &$array in the function definition, not $array This will pass in the actual array, so that you can modify it in place. Otherwise you would just be passing in a copy.
Assuming you trust the contents of the variable containing your array indices, this is a completely valid use of eval:
$keys = array(1,5,3,4,6);
$keys = "[" . join($keys, "][") . "]";
$value = "what";
eval("\$array$keys = '$value';"); # $array[1][5][3][4][6] = 'what';
Here's a solution without using eval. Go through each key and reduce the array as you go. The $ref variable below is a reference to the original array so changing it will change the original.
$keys = array(1,5,3,4,6);
$array[1][5][3][4][6] = 'foo';
$ref = &$array;
foreach( $keys as $key ) {
$ref = &$ref[ $key ];
}
$ref = 'bar';
echo $array[1][5][3][4][6]; // 'bar'
This is untested. I tend to shy away from using references because I think they're particularly confusing, and they leave remnant reference in your code that can cause difficult to find bugs.
$keys = array(1,5,3,4,6);
$path = 'new leaf value';
foreach (array_reverse($keys) as $key) {
$path = array($key => $path);
}
$modified = array_replace_recursive($origionalArray, $path);
I have an array thats got about 12 potential key/value pairs. That are based off a _POST/_GET
The keys are not numeric as in 0-n, and I need to retain the keys with there values where applicable. My issue is I know that on occasion a key will be passed where the value is null, empty, or equal to ''. In the event thats the case I want to trim out those keys before processing my array. As running down the line without something there is going to break my script.
Now a while back I either made or found this function (I don't remember which its been in my arsenal for a while, either way though).
function remove_array_empty_values($array, $remove_null_number = true)
{
$new_array = array();
$null_exceptions = array();
foreach($array as $key => $value)
{
$value = trim($value);
if($remove_null_number)
{
$null_exceptions[] = '0';
}
if(!in_array($value, $null_exceptions) && $value != "")
{
$new_array[] = $value;
}
}
return $new_array;
}
What I would love to do is very similar to this, however this works well with arrays that can have n-n key values and I am not dependent upon the key as well as the value to determine whats what where and when. As the above will just remove everything basically then just rebuilt the array. Where I am stuck is trying to figure out how to mimic the above function but where I retain the keys I need.
If I understand correctly what you're after, you can use array_filter() or you can do something like this:
foreach($myarray as $key=>$value)
{
if(is_null($value) || $value == '')
unset($myarray[$key]);
}
If you want a quick way to remove NULL, FALSE and Empty Strings (""), but leave values of 0 (zero), you can use the standard php function strlen as the callback function:
// removes all NULL, FALSE and Empty Strings but leaves 0 (zero) values
$result = array_filter( $array, 'strlen' );
Source: http://php.net/manual/en/function.array-filter.php#111091
array_filter is a built-in function that does exactly what you need. At the most you will need to provide your own callback that decides which values stay and which get removed. The keys will be preserved automatically, as the function description states.
For example:
// This callback retains values equal to integer 0 or the string "0".
// If you also wanted to remove those, you would not even need a callback
// because that is the default behavior.
function filter_callback($val) {
$val = trim($val);
return $val != '';
}
$filtered = array_filter($original, 'filter_callback');
if you want to remove null, undifined, '', 0, '0', but don't remove string ' '
$result = array_filter( $array, 'ucfirst' );
Filtering the array for PHP 7.4 and above use this
// Filtering the array
$result = array_filter($array, fn($var) => ($var !== NULL && $var !== FALSE && $var !== ""));
use +1 with your key variable to skip null key in array
foreach($myarray as $key=>$value)
{
echo $key+1; //skip null key
}
I am looking for away to check if a string exists as an array value in an array is that possible and how would I do it with PHP?
If you simply want to know if it exists, use in_array(), e.g.:
$exists = in_array("needle", $haystack);
If you want to know its corresponding key, use array_search(), e.g.:
$key = array_search("needle", $haystack);
// will return key for found value, or FALSE if not found
You can use PHP's in_array function to see if it exists, or array_search to see where it is.
Example:
$a = array('a'=>'dog', 'b'=>'fish');
in_array('dog', $a); //true
in_array('cat', $a); //false
array_search('dog', $a); //'a'
array_search('cat', $a); //false
Php inArray()
Incidentally, although you probably should use either in_array or array_search like these fine gentlemen suggest, just so you know how to do a manual search in case you ever need to do one, you can also do this:
<?php
// $arr is the array to be searched, $needle the string to find.
// $found is true if the string is found, false otherwise.
$found = false;
foreach($arr as $key => $value) {
if($value == $needle) {
$found = true;
break;
}
}
?>
I know it seems silly to do a manual search to find a string - and it is - but you may one day wish to do more complicated things with arrays, so it's good to know how to actually get at each $key-$value pair.
Here you go:
http://www.php.net/manual/en/function.array-search.php
The array_search function does exactly what you want.
$index = array_search("string to search for", $array);
Say we have this array:
<?php
$array = array(
1 => 'foo',
2 => 'bar',
3 => 'baz',
);
?>
If you want to check if the element 'foo' is in the array, you would do this
<?php
if(in_array('foo', $array)) {
// in array...
}else{
// not in array...
}
?>
If you want to get the array index of 'foo', you would do this:
<?php
$key = array_search('foo', $array);
?>
Also, a simple rule for the order of the arguments in these functions is: "needle, then haystack"; what you're looking for should be first, and what you're looking in second.