PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, April 19, 2022

[FIXED] How to merge array with custom value in laravel?

 April 19, 2022     arrays, laravel, php     No comments   

Issue

I need help to concatenate 2 arrays with custom values, I've used tried array_merge() and array_combine(), the result is always not same with what I want please help me guys

Array 1

$month = [
'January',
'January',
'January',
'January',
'February'
];

Array 2

$weeks = [
'Week 1',
'Week 2',
'Week 3',
'Week 4',
'Week 1'
];

I want the output be like this

$newArray = [
'January - Week 1',
'January - Week 2',
'January - Week 3',
'January - Week 4',
'February - Week 1'
];

how to get the result like that


Solution

There isn't any function that will automatically give you the result you want. You need to iterate through the data and create it yourself:

$month = [
    'January',
    'January',
    'January',
    'January',
    'February'
];

$weeks = [
    'Week 1',
    'Week 2',
    'Week 3',
    'Week 4',
    'Week 1'
];

$newArray = [];

foreach ($month as $index => $value) {
    // Create the new string you want, using the same index for both arrays
    $newArray[] = $value . ' - ' . $weeks[$index];
}

Demo: https://3v4l.org/7qAoX



Answered By - M. Eriksson
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing