dolor3sh4ze
dolor3sh4ze

Reputation: 1165

Search in array with foreach

I am currently pushing with different inputs in my request with a different key each time. Is there a way to search for a key containing "-id" for example?

Here is my request result (with a dd):

request result

My goal would be to do a

foreach($request->contains('id') as $id) {
      //DOING SOME THINGS
}

I tried to do this with different PHP functions like strpos() or strpos_recursive() but either the functions don't exist or it doesn't do the expected result. The goal would also be to be able to retrieve the values associated with the keys.

Upvotes: 0

Views: 291

Answers (2)

xNoJustice
xNoJustice

Reputation: 594

foreach(array_keys($request) as $r => $val){
    if(strpos($val, 'id')){
        //...
    }
}

array_keys function give keys in your array. I received the value of these keys with the foreach loop. I checked if the keys contain id with strpos function. In this way, I reached the desired result.

Upvotes: 0

Watercayman
Watercayman

Reputation: 8178

Laravel provides some nice functions to help you to do this. First, using all() within the standard request object, you can see the items coming in through the input. Then using the Helper function contains you can get what you need:

public function update(Request $request){
    foreach($request->all() as $key=>$val) {
          if(Str::contains($key, '-id')){
              // etc..

Also, the built-in function has() may help you without having to loop, as well, if the key is exactly 'id', but I think the above is more what you are looking for:

if($request->has('id')){
     $id = $request->input('id');
     // do something
}

Upvotes: 2

Related Questions