Reputation: 33
I am working a form where i have to adopt associative array technique. the user will select a product size and enter the corresponding stock. once post the corresponding stock will be associated to the corresponding size value. Here is the form:
<form action="test1.php" method="post">
<p>Choose a Size or more and enter its Stock</p>
Size :<select name="articleSize[]" id="articleSize[]">
<option value="">Select a size</option>
<option value="xl">XL</option>
<option value="32">32</option>
<option value="unique">Unique</option>
<option value="xxl">XXL</option>
</select>
Stock : <input type="text" name="articleStock[]" id="articleStock[]" size="8" id="stock" value="">
<p>Choose a Size or more and enter its Stock (optional)</p>
Size :<select name="articleSize[]" id="articleSize[]">
<option value="">Select a size</option>
<option value="xl">XL</option>
<option value="32">32</option>
<option value="unique">Unique</option>
<option value="xxl">XXL</option>
</select>
Stock : <input type="text" name="articleStock[]" id="articleStock[]" size="8" id="stock" value="">
<p>
<input type="submit" name="submit" id="submit" value="submit">
</p>
</form>
I have tried myself based on what i know and here is my code:
if (isset($_POST['submit'])) {
$arrSize = $_POST['articleSize'];
$arrStock = $_POST['articleStock'];
foreach ($arrSize as $size_key => $sizeValue) {
foreach ($arrStock as $stock_Key => $stockVal) {
if ($size_key == $stock_Key) {
$newArray[$sizeValue] = $stockVal;
}
}
}
if (count($newArray) >=1) {
foreach ($newArray as $key => $value) {
echo "Size is ".$key. " and stock is ".$value;
}
}
}
My code is working as excepted but is't there better way to do it?
The result shoud be like.
$stock_size = array(the size=> its corresponding stock);
Upvotes: 2
Views: 66
Reputation: 54841
You can eliminate inner foreach
like this:
foreach ($arrSize as $size_key => $sizeValue) {
if (!empty($arrStock[$size_key])) {
$newArray[$sizeValue] = $arrStock[$size_key];
}
}
If there's a need to count 0
values too you can:
foreach ($arrSize as $size_key => $sizeValue) {
if (!empty($arrStock[$size_key]) && (int)$arrStock[$size_key] >=0 ) {
$newArray[$sizeValue] = $arrStock[$size_key];
}
}
And if you're sure that all values have pairs:
foreach ($arrSize as $size_key => $sizeValue) {
$newArray[$sizeValue] = $arrStock[$size_key];
}
which is the same as
$newArray = array_combine($arrSize, $arrStock);
Update with function:
function makePairs($arrSize, $arrStock)
{
$newArray = [];
foreach ($arrSize as $size_key => $sizeValue) {
if (!empty($arrStock[$size_key])) {
$newArray[$sizeValue] = $arrStock[$size_key];
}
}
return $newArray;
}
// Call like
print_r(makePairs($_POST['articleSize'], $_POST['articleStock']));
Upvotes: 1
Reputation: 16436
You can use array_combine
which will create key-value
pair array
$arrSize = $_POST['articleSize'];
$arrStock = $_POST['articleStock'];
$stock_size = array_combine ( $arrSize ,$arrStock );
Upvotes: 0