0

I'm trying to get the bottom values of an array with two conditions as below :

  1. Get all numeric values from the bottom until the next value is a string then stop the instruction, and leave all other values even if they are numeric
  2. If the first values from the bottom are strings skip them and execute the first condition.

<?php $data=[1,2,3,'web',4,5,6,'web',7,8,9]; ?>

The output will be 7 8 9.

<?php $data= [1,2,3,'web',4,5,6,'web',7,8,9,'web','web']; ?>

<?php $data= [1,2,3,'web',4,5,6,'web',7,8,9,'web']; ?>

Both of conditions will have the same output: 7 8 9.

2
  • I have tried this solution and it works for the first condiotion : <?php $data = [1,2,3,'web',4,5,6,'web',7,8,9]; $newArray = array(); // resultant array foreach ($data as $key => $value) { if(is_int($value)){ $newArray[] = $value; } else{ $newArray = array(); // reset if not integer } } echo "<pre>"; print_r($newArray); ?> Commented Jul 9, 2019 at 18:21
  • 1
    Please add the I have tried code to your original question. Commented Jul 9, 2019 at 20:31

1 Answer 1

1

Logic: Reverse the array and check weather the given element is integer, if it is an integer, put it into a temporary array, otherwise, check if the process of saving integer data has already been started, if yes, break the loop otherwise, continue with the loop. Finally, reverse the array again to get the data in same format.

<?php
$data= [1,2,3,'web',4,5,6,'web',7,8,9,'web'];
$process = false;
foreach(array_reverse($data) as $d){
    if(is_int($d)){
        $process = true;
        $temp[] = $d;
    }
    else if($process) break;
}
$result = array_reverse($temp);
print_r($result);
?>
Sign up to request clarification or add additional context in comments.

1 Comment

@ahmedhendah, if it worked for you, please upvote and green-tick the answer :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.