I want to try take only filled rows to another array via array_push but i can't take them dynamically because first index is string, how can i do it properly? Thanks.
<?php
while($i < count($val['error']){
if($val['error'][$i] === 0)
{
array_push($newarray, $val[whatwilliputherebecauseofstringindex][$i]);
}
}
?>
Hi here is the pastebin
<?php
// get keys of original array (name, type, etc..)
$keys = array_keys($array);
// for each error value ...
foreach ($array['error'] as $key => $val) {
// if error is not 0..
if($val !== 0)
{
// for each key in the original array..
foreach ($keys as $k) {
// unset the element of the same iteration
unset($array[$k][$key]);
}
}
}
?>
Related
I have two arrays of objects like
$array1 = [{id: '12',amount:'23'},{id:'10',amount:'129'},{id:'8', amount:'47'}];
$array2 = [{id: '3', date:'23'},{id:'4', date:'12'},{id:'6', date:'21'}];
I want to check all the id (12,10,8) of the first array to the second.
if those ids are not present in array 2. it will var_dump('not matched').
I tried to do this, but when fist element not matched it was stopped to iterate further and show 'not found' status.
foreach ($array1 as $value) {
foreach ($array2 as $value2) {
if ($value['id'] !== $value2['id']) {
var_dump('not found');
}
}
}
I expect to show the output result after all iteration is done.
You can use array_diff with array_column
if(!array_diff(array_column($array1, 'id'), array_column($array2, 'id'))){
echo 'Not matched';
}
Thanks for helping me out but,
I just found a solution, I use a loop iteration counter.
It counts the iteration number and checks that it completes all the iteration according to the array length.
foreach ($array1 as $value) {
$notFound = 0;
foreach ($array2 as $value2) {
if ($value['id'] === $value2['id']) {
var_dump('match found')
}
} else {
$notFound++;
}
}
if ($notFound === count($array2)) {
var_dump('not found')
}
}
I have student exam scores in an array and want to show only the first and last exam score when student selects for
how do I show first and last element only of an array with foreach loop in PHP.
so far I have done the below method which works for me but it seems not an efficient method
$y = 0;
$student_total_sessions = $total_counter = sizeof($student_exam_session_data);
if($this->data['show_sessions'] != 'all_sessions')
{
$student_total_sessions = ($student_total_sessions > 2) ? 2 : $student_total_sessions;
}
foreach ($student_exam_session_data as $student_session_id => $student_session_data)
{
$y++;
// only show first and last in case show sessions is pre and post
if($this->data['show_sessions'] != 'all_sessions' && $y > 1 && $y != $total_counter)
{
continue;
}
else
{
echo $student_session_data['exam_score'];
}
}
To display the first element of array
echo $array[0];//in case of numeric array
echo reset($array);// in case of associative array
To display the last element
echo $array[count($array)-1];//in case of numeric array
echo end($myArray);// in case of associative array
If your array has unique array values, then determining the first and last element is trivial:
foreach($array as $element) {
if ($element === reset($array))
echo 'FIRST ELEMENT!';
if ($element === end($array))
echo 'LAST ELEMENT!';
}
This works if last and first elements are appearing just once in an array, otherwise you get false positives. Therefore, you have to compare the keys (they are unique for sure).
foreach($array as $key => $element) {
reset($array);
if ($key === key($array))
echo 'FIRST ELEMENT!';
end($array);
if ($key === key($array))
echo 'LAST ELEMENT!';
}
I wrote a blog post about exactly this a while back. Basically:
// Go to start of array and get key, for later comparison
reset($array)
$firstkey = key($array);
// Go to end of array and get key, for later comparison
end($array);
$lastkey = key($array);
foreach ($array as $key => $element) {
// If first element in array
if ($key === $firstkey)
echo 'FIRST ELEMENT = '.$element;
// If last element in array
if ($key === $lastkey)
echo 'LAST ELEMENT = '.$element;
} // end foreach
OR for PHP 7.3 and up use array_key_first and array_key_last:
foreach($array as $key => $element) {
// If first element in array
if ($key === array_key_first($array))
echo 'FIRST ELEMENT = '.$element;
// If last element in array
if ($key === array_key_last($array))
echo 'LAST ELEMENT = '.$element;
} // end foreach
I am writing a shopping cart session handler class and I find myself repeating this certain chunk of code which searches a multidimensional associative array for a value match.
foreach($_SESSION['cart'] as $k => $v){
if($v['productID'] == $productID){
$key = $k;
$this->found = true;
}
}
I am repeating this when trying to match different values in the array.
Would there be an easy to to create a method whereby I pass the key to search and the value. (Sounds simple now I read that back but for some reason have had no luck)
Sounds like you want something like this:
function findKey(array $array, $wantedKey, $match) {
foreach ($array as $key => $value){
if ($value[$wantedKey] == $match) {
return $key;
}
}
}
Now you can do:
$key = findKey($_SESSION['cart'], 'productID', $productID);
if ($key === null) {
// no match in the cart
} else {
// there was a match
}
I have a string of 7 numbers in an array looks like 4,1,2,56,7,9,10 however sometimes these elements are empty ,,,56,7,9,10 for example. What I would like to do is reorder the array so it looks like 56,7,9,10,,,
try this:
$null_counter = 0;
foreach($array as $key => $val) {
if($val == null) {
$null_counter++;
unset($array[$key]);
}
}
for($x=1;$x<=$null_counter;$x++) {
$array[] = null;
}
Use unset in loop to remove null value and shift the values Up.
foreach($yourarray as $key=>$val )
{
if($yourarray[$key] == '')
{
unset($yourarray[$key]);
}
}
I have a PHP array of associative arrays with the following format:
array(1) {
[0]=>
{ ["name"]=> "Steve Jobs"
["email"]=> "steve#gmail.com" }
}
I'm very new to PHP, but what I want to do is search for a specific email, and if found, delete that specific array (name & email pair) from the array (without leaving an empty space in the array where the removed object used to be).
I found this code here that searches for an entry but returns an array. How would I modify this to delete the found array?
function search($array, $key, $value)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && $array[$key] == $value)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, search($subarray, $key, $value));
}
return $results;
}
Something like this?
function delete_user(&$arr, $name){
for($i = count($arr)-1; $i >= 0; $i--){
if($arr[$i]["name"] == $name){
unset($arr[$i]);
}
}
}
the &$arr tells PHP to pass the array by reference, so it can be modified from the function, otherwise, it'll be pass-by-value.
You have to use unset to remove an element and use in_array or array_search method to search an element from an array.
unset($array[0]);
Sample from PHP manual (array_search)
function array_key_index(&$arr, $key) {
$i = 0;
foreach(array_keys($arr) as $k) {
if($k == $key) return $i;
$i++;
}
}
I believe there's a small problem with raser's answer. I tried to comment on it, but I can't since I don't have 50 reputation.
Let me know if you agree: count($arr) returns the number of elements in the array. He's using a decremental for loop, except the array's index starts at 0 and his loop ends before it reaches 0, so the first element of the array is never searched. I believe the correct code would be something like:
function delete_user(&$arr, $name){
for($i = count($arr) - 1; $i >= 0; $i--){
if($arr[$i]["name"] == $name){
unset($arr[$i]);
}
}
}
Thanks!
just found array index, and
unset(array(key));
this will not showing that array