Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

FareedR's avatar

in_array key and list of data

so i got a form that need to tick (checkbox). and the tick(checkbox) is an array . am i missing somewhere ?

$is_contradicts    = $request->has('contradict');
$contradicts = [];

if($is_contradicts){
	$contradicts = $request->get('contradict');
}

foreach ($time_frames as $key => $time_frame){
	$analysis = new Analysis([
		'stock_id'      => $stock->id,
                'time_frame'    => $time_frame,
                'description'   => $descriptions[$key],
                'is_contradict' => in_array($key,$contradicts) ? 1 : 0
	]);
	$analysis->save();
}
//example contradicts
0 => '1'

dd(in_array($key,$contradicts); // false -- supposedly true right ??

//result
// db analyses
stock_id | time_frame | description | is_contradict
1			10			Week		0

// expected result
// db analyses
stock_id | time_frame | description | is_contradict
1			10			Week		1

0 likes
3 replies
bugsysha's avatar

$key is changing on every loop and your check is outside of the loop. Also $contradicts is probably not an array. Check that.

frankincredible's avatar

Can you be more explicit with what these variables contain by dumping the following:

dump($request('contradict'));

dump($time_frames); I'm going to assume that $time_frames looks something like this:

$time_frames = [
    0 => 'Day',
    1 => 'Week',
    2 => 'Month',
    3 => 'Year',
];

And then request('contradicts') looks something like this to mean something like "the user has chosen to contradict the timeframes with a key of 0 (Day) and 3 (Month)":

[
    0 => 1,
    3 => 1,
]

If my assumptions are accurate, then you can do something like this:

// In reality you'd use request('contradict'),
// but since I don't have your request() object, 
// I'm manually assigning the array to a $contradictions array
$contradictions = [
    0 => 1,
    3 => 1,
];

$time_frames = [
    0 => 'Day',
    1 => 'Week',
    2 => 'Month',
    3 => 'Year',
];

foreach ($time_frames as $key => $time_frame){
    // $analysis = new Analysis([
    //     'stock_id'      => $stock->id,
    //     'time_frame'    => $time_frame,
    //     'description'   => $descriptions[$key],
    //     'is_contradict' => $contradictions[$key] ?? 0
    // ]);
    // $analysis->save();
  
    // I don't have $stock or $descriptions, so I just created string constants for those.
    dump([
        'stock_id'      => 'stock_id',
        'time_frame'    => $time_frame,
        'description'   => "Description for key: {$key}",
        'is_contradict' => $contradictions[$key] ?? 0,
    ]);
}
FareedR's avatar

my mistake on frontend . it solved now

Please or to participate in this conversation.