I'm curious, more than anything - is it possible to get a PHP value posted? i.e. $_POST['foo'] via some kind of indexing? i.e. $_POST[0]?
($_POST[0] does not work by the way)
No, it's not possible: you cannot fetch values from an associative array by numeric indexes (because, as clearly noted in the doc, PHP does not distinguish between indexed and associative arrays).
That's why some functions (PDOStatement::fetch and its siblings, for example) that return arrays take an additional param to control the 'type' of indexes in the array returned: numeric (FETCH_NUM), string (FETCH_ASSOC) or both (FETCH_BOTH, the default value). )
The closest you might get with reindexing:
$myPost = array_values($_POST);
not that i'm aware of, check out a print_r($_POST) to see all goodies that you can access. You could iterate over the values with:
foreach($_POST as $key=>$value){
echo $key.' '.$value."\n";
}
You could throw in an $i++ if you wanted to keep track of a count ....
You can take data stored in $_POST variables and store them into indexed elements. But they are not stored as an indexed element initially.
Related
I need to find the most common (most occurring) array in a multidimensional array. Not the most common values like this post - Find Common most values in multidimensional array in PHP - but rather the most common combination.
For example, if I have the following:
$a1=array(
array('704322062'),
array('678073776', '704322062'),
array('678073776', '704322062'),
array('704322064'),
array('704322062'),
array('678073776'),
array('678073776', '704322062')
);
I want to be able to detect that the array that occurs most often is array('678073776', '704322062') not that the string '704322062' is most common.
I've tried using array_intersect but couldn't get it working for this scenario.
Thanks!
array_count_values only works with scalar values, not when the items are arrays themselves. But we can still use that function, if we transform your arrays into strings first - by encoding them as JSON.
// fill temp array with items encoded as JSON
$temp = [];
foreach($a1 as $item) {
$temp[] = json_encode($item);
}
// count how many times each of those values occurs
$value_counts = array_count_values($temp);
// sort by number of occurrence, while preserving the keys
ksort($value_counts);
// pick the first key from the temp array
$first = array_key_first($value_counts);
This will get you ["678073776","704322062"] in $first now - you can json_decode it again, if you want your “original” array.
Note that this does not take into account, that two arrays could occur the same amount of times - then it will just pick the “random” first one of those. If you need to handle that case as well somehow, then you can determine the maximum value in $temp first, and then filter it by that value, so that only those keys of the corresponding arrays will be left.
Which one would you use?
Basically I only want to get the 1st element from a array, that's it.
Well, they do different things.
array_shift($arr) takes the first element out of the array, and gives it to you.
$arr[0] just gives it to you... if the array has numeric keys.
An alternative that works for associative arrays too is reset($arr). This does move the array's internal pointer, but unless you're using those functions this is unlikely to affect you.
array_shift will actually remove the specified value from the array. Do not use it unless you really want to reduce the array!
See here: http://php.net/manual/en/function.array-shift.php
You would use $arr[ 0 ]; array_shift removes the first element from the array.
EDIT
This answer is actually somewhere between incomplete and plain out wrong but, because the comments of the two jon's I think that it should actually stay up so that others can see that discourse.
The right answer:
reset is the method to return the first defined index of the array. Even in non-associative arrays, this may not be the 0 index.
array_shift will remove and return the value which is found at reset
The OP made the assumption that $arr[0] is the first index is not accurate in that particular context.
$arr[0] only works if the array as numerical keys.
array_shift removes the element from the array and it modifies the array itself.
If you are not sure what the first key is , and you do not want to remove it from the array, you could use:
<?php
foreach($arr $k=>$v){
$value = $v;
break;
}
or even better:
<?php
reset($arr);
$value = current($arr);
If you have an associative Array you can also use reset($arr): It returns the first Element (doesn't remove), and sets the array pointer to this element.
But the fastest way is $arr[0].
Do you want to modify the arr array also? array_shift removes the first element of the array and returns it, thus the array has changed. $arr[0] merely gives you the first element.
I would use $arr[0] unless I explicitly wanted to modify the array. You may add code later to use the arr array and forget that it was modified.
given what you need, $arr[0] is preferrable, because it's faster. array_shift is used in other situations.
arrshift is more reliable and will always return the first element in the array, but this also modifies the array by removing that element.
arr[0] will fail if your array doesn't start at the 0 index, but leaves the array itself alone.
A more convoluted but reliable method is:
$keys = array_keys($arr);
$first = $arr[$keys[0]];
with array_shif you have two operations:
retrive the firs element
shift the array
if you access by index, actually you have only one operation.
If you want the first element of an array, use $arr[0] form. Advantages - Simplicity, Readability and Maintainability. Keep things straight forward.
Edit: Use index 0 only if you know that the array has default keys starting from 0.
If you don't want to change the array in question, use $arr[0] (which merely gets the first element), otherwise if you want to remove the first element of $arr from $arr, use array_shift($arr).
For example:
$arr=array(3,-6,2);
$foo=$arr[0]; //$foo==3 and $arr==array(3,-6,2).
$bar=array_shift($arr); //$bar==3 and $arr==array(-6,2).
ETA: As others have pointed out, be sure that your array isn't an associative array (ie the keys are 0,1,...,(sizeof($arr)-1)), otherwise this probably won't work.
What is difference between $prefix=array(''=>''); and $prefix=array();
what exactly $prefix=array(''=>''); using for ?
There isn't really a difference, both are arrays. The difference is, the latter has an array key.
For instance,
$test1=array(1,2,3,4,5);
$test2=array('name'=>'bob','lastname'=>'fossil');
will return;
print_r($test1[0]);
//1
print_r($test2['name']." ".$test2['lastname']);
//bob fossil
Basically, it gives the value a name
key=>val
can be used like this
foreach($test2 as $val){
echo$val;
}
//bob
//fossil
It's used for creating associative arrays
No difference. first option creates an array with some elements at once, the second creates an empty array.
This is probably a very trivial question, but please bear with me.
I am trying to read a lot of data into an array of associative arrays. The data contains a lot of empty arrays and arrays with keys set and but all null values. I want to ignore those and only push arrays with at least one key mapped to a non-null value. (The data comes from an excel sheet and it has lots of empty cells that are registered as "set" anyway.) So far I have tried:
if(!empty(${$small_dummy}))
array_push(${$big_dummy}, ${$small_dummy});
That gets rid of the empty arrays but not the ones where all keys map to null. Is there a better way to do this than looping through the entire array and popping all null values?
Judging by the code you have already, you can change:
if(!empty(${$small_dummy}))
to:
if(!empty(array_filter(${$small_dummy})))
That will filter out all empty values (values evaluating to FALSE to be precise) and check if the resulting array is empty. Also see the manual on array_filter().
Note that this would also filter 0 values so you might need to write a custom callback function for array_filter().
You can try if(!array_filter($array)) { also
This isn't an ideal approach, but array_sum will return 0 if all values can't be cast to a numeric value. So :
$small_dummy = array("a" => null, "foo", "", 0);
if(array_sum($small_dummy) === 0)
would pass. But this is only the way to go if you are expecting the values to be numeric.
Actually, if the problem is that the array keys have values and therefor are not passing as empty(), the go with array_values:
if(!empty(array_values(${$small_dummy})))
It seems to work, but it feels wrong, I assume it is.
Is it wrong?
If so, I currently have an array with keys being mysql database id's and the values being their values.
Would it be better to have the key being "record_"+$id and then explode()ing the key and getting the id from that?
Or is it ok to set your own array keys, and php will just assume they are assoc array keys, rather than indexes?
Thanks
Some built-in PHP functions (like array_merge / array_multisort) will re-index your array:
array_merge() If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If,
however, the arrays contain numeric keys, the later value will not
overwrite the original value, but will be appended. Values in the
input array with numeric keys will be renumbered with incrementing
keys starting from zero in the result array.
array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions. Associative
(string) keys will be maintained, but numeric keys will be re-indexed.
I would advise you not to do that, use a proper value instead, or at the very least prefix it with a short _:
foreach ($array as $key => $value)
{
$id = ltrim($key, '_');
// do stuff with the actual $id
}