PHP: simple array operation - php

I have an array like this (one dimension only):
$arr = array('one', 'two', 'three', 'foo', 'bar', 'etc');
Now I need a for() loop that creates a new array from $arr, like that:
$newArr = array('one', 'onetwo', 'onetwothree', 'onetwothreefoo', 'onetwothreefoobar', 'onetwothreefoobaretc');
Seems to be simple but I can't figure it out.
Thanks in advance!

$mash = "";
$res = array();
foreach ($arr as $el) {
$mash .= $el;
array_push($res, $mash);
}

$newArr = array();
$finish = count($arr);
$start = 0;
foreach($arr as $key => $value) {
for ($i = $start; $i < $finish; $i++) {
if (isset($newArray[$i])) {
$newArray[$i] .= $value;
} else {
$newArray[$i] = $value;
}
}
$start++;
}

Related

PHP Merging arrays with for loops without using array_merge function

I am learning more about for loops and would like to see how do you merge arrays using only for loops and not using built-in PHP functions such as array_merge().
I know you can use foreach to do this, but how would this work using only for loops and not foreach?
foreach example:
$array1 = ['judas', 'john', 'michael'];
$array2 = ['fernando', 'jsamine', 'sam', 'walter'];
$array3 = ['judas', 'john', 'mike', 'steve'];
foreach ([$array1, $array2, $array3] as $arr) {
foreach ($arr as $values) {
...
}
}
Yes, you can do this using just for loops.
$array1 = ['judas', 'john', 'michael'];
$array2 = ['fernando', 'jsamine', 'sam', 'walter'];
$array3 = ['judas', 'john', 'mike', 'steve'];
$all_arrays = [$array1, $array2, $array3];
$merged = [];
for ($i = 0; $i < 3; $i++) {
$arr = $all_arrays[$i];
$x = count($arr);
for ($j=0; $j < $x; $j++) {
// Using the value as the key in the merged array ensures
// that you will end up with distinct values.
$merged[$arr[$j]] = 1;
}
}
// You could use array_keys() to do get the final result, but if you
// want to use just loops then it would work like this:
$final = [];
$x = count($merged);
for ($i=0; $i < $x; $i++) {
$final[] = key($merged);
next($merged);
}
var_dump($final);
key() and next() ARE php functions. But I really do not know of a way to get to the keys without using either foreach or some php function.
Iterate each array on its own:
foreach($array2 as $v)
if(!in_array($v, $array1))
$array1[] = $v;
foreach($array3 as $v)
if(!in_array($v, $array1))
$array1[] = $v;
Or simply use array_merge() - there is no reason for do not do it.
$a=array('1','2','3','4','5');
$b=array('a','b','c','d','e');
$c=count($b);
for($i=0; $i<$c; $i++)
{
$a[]=$b[$i]; // each element 1 by 1 store inside the array $a[]
}
print_r($a);
function arrayMerge(array $arrays) {
$mergeArray = [];
foreach ($arrays as $key => $array) {
foreach($array as $finalArray) {
$mergeArray[] = $finalArray;
}
}
return $mergeArray;
}
$array1 = [
'Laravel', 'Codeigniter', 'Zend'
];
$array2 = [
'Node js', 'Vue js', 'Angular js'
];
$array3 = [
'Python', 'Django', 'Ruby'
];
print_r(arrayMerge([$array1, $array2, $array3]));
$arr1 = array(1,2,3,4,5);
$arr2 = array(2,5,6,7,8);
$allval = array();
foreach($arr2 as $key=>$val){
$arr1[] = $val;
}
foreach($arr1 as $k=>$v){
if(!in_array($v,$allval)){
$allval[] = $v;
}
}
echo "<pre>"; print_R($allval);

PHP combines 2 arrays

I have 2 arrays in php
$array1[] = a,b,c,d,e;
$array2[] = 1,2,3,4,5;
$data = array('letter'=>$array1,'num'=>$array2);
return json_encode($data);
This will return:
[[a,b,c,d,e],[1,2,3,4,5]]
I'd like to return it in json_encode like this:
$data = [[1a,1],[b,2],[c,3],[d,4],[e,5]];
Can someone help me with this?
this is the simplest solution
$result = array();
foreach ($array1 as $k1 => $v1) {
$result[] = array($v1, $array2[$k1]);
}
echo json_encode($result)
but arrays must have the same length and same keys
Try below code, it is flexible and don't have to care about the length of the arrays.
<?php
$letters = array('a','b','c','d','e');
$numbers = array('1','2','3','4','5');
$counter = (sizeof($letters) > sizeof($numbers)) ? sizeof($letters) : sizeof($numbers);
$arr = array();
for($i=0; $i<$counter; $i++)
{
if(array_key_exists($i, $letters))
$arr[$i][] = $letters[$i];
if(array_key_exists($i, $numbers))
$arr[$i][] = $numbers[$i];
}
$json = json_encode($arr);
echo $json;
Output:
[["a","1"],["b","2"],["c","3"],["d","4"],["e","5"]]
Demo:
http://3v4l.org/7v7X4
What you are looking for is the function array_combine().
Here is an example:
$array1 = array("a","b","c","d","e");
$array2 = array(1,2,3,4,5);
$data = array_combine($array1, $array2);
$new_data = array();
foreach($data AS $key => $value) {
$new_data[] = array($key, $value);
}
print_r(json_encode($new_data));
Which should return something like:
[["a",1],["b",2],["c",3],["d",4],["e",5]]
UPDATE Changed the code to give the result wanted...

Dynamically populate php array using foreach loop

How can I implement the code:
$numberList3 = array();
for($i = 0; $i < 10; $i++)
{
$numberList3[$i] = $i;
}
print_r($numberList3);
Using a foreach loop as the no. of times the loop is going to execute is decided by the user at run time.
Any suggestion.?
Use array_fill maybe?
<?php
$n = 10;
$arr = array_fill(0,$n,0);
foreach($arr as $k => $v) {
$arr[$k] = $k;
}
print_r($arr);
Or, as suggested by #deceze, use range
<?php
$n = 10;
$arr = array();
foreach(range(0,$n-1) as $v) {
$arr[$v] = $v;
}
print_r($arr);
Or when the value is the same as the key, you can use just this:
<?php
$n = 10;
$arr = range(0,$n-1);
// no foreach needed
print_r($arr);
foreach() works for object and array not for a single value.
What you can do create an array or object from users input.
like:
$userInput = 10;
$forEachArray = array_fill(0, $userInput, 0);
$arrayToDisplay = array();
foreach($forEachArray as $key){
$arrayToDisplay[$key] = $key;
}
print_r($arrayToDisplay);

Array replace not working

The below is my array, where I need to replace the value of 'battle_health'
$battlepokemon= array();
$i = 1;
while($rows = mysql_fetch_assoc($res))
{
$path = mysql_query(" SELECT * FROM pokemons WHERE pk_id = '".$rows['pkmn_id']."' ");
$pokemon = array(
'opponent_increment' => $i,
'id' => $rows['pkmn_id'],
'battle_poke'=> mysql_result($path,0,"path"),
'battle_level' => $rows['level'],
'battle_health' => $rows['health']
);
$i++;
$battlepokemon[]= $pokemon;
}
The code for replacement is:
$i = 1;
foreach ($battlepokemon as $key => $value)
{
if($value['opponent_increment'] == $opponent_increment)
{
$value['battle_health'] = 0;
echo "Data replaced!";
}
$i++;
}
print_r($battlepokemon);
The code above is working..from start to end.. but the value is not replaced with '0' as the code says!
I think I must have missed something!
You need to transfer the reference, not the values. Add a & to the following sentence
foreach ($battlepokemon as $key => &$value)
^
I tried this just for example
<?php
$arr = array('12', '34');
foreach($arr as $key => &$value){
$value = 0;
}
var_dump($arr);
?>
Hopes it can help you
You can achieve this with for Loop Because unlike foreach loop, it doesn't perform an array copy before transversal:
$arr = array('12', '34');
for($i = 0, $count = count($arr); $i < $count; $i++){
$arr[$i] = 0;
}
var_dump($arr);
Or If you want to do with Foreach only, you need to avoid new copy of array by passing the reference like:
$arr = array('12', '34');
foreach($arr as $key => &$value)
{
$value = 0;
}
var_dump($arr);

How to convert every two consecutive values of an array into a key/value pair?

I have an array like the following:
array('category_name:', 'c1', 'types:', 't1')
I want the alternate values of an array to be the values of an array:
array('category_name:' => 'c1', 'types:' => 't1')
You could try: (untested)
$data = Array("category_name:","c1","types:","t1"); //your data goes here
for($i=0, $output = Array(), $max=sizeof($data); $i<$max; $i+=2) {
$key = $data[$i];
$value = $data[$i+1];
$output[$key] = $value;
}
Alternatively: (untested)
$output = Array();
foreach($data as $key => $value):
if($key % 2 > 0) { //every second item
$index = $data[$key-1];
$output[$index] = $value;
}
endforeach;
function fold($a) {
return $a
? array(array_shift($a) => array_shift($a))
+ fold($a)
: array();
}
print_r(fold(range('a','p' )));
~)
upd: a real-life version
function fold2($a) {
$r = array();
for($n = 1; $n < count($a); $n += 2)
$r[$a[$n - 1]] = $a[$n];
return $r;
}
Here is another yet complex solution:
$keys = array_intersect_key($arr, array_flip(range(0, count($arr)-1, 2)));
$values = array_intersect_key($arr, array_flip(range(1, count($arr)-1, 2)));
$arr = array_combine($keys, $values);
$array = your array;
$newArray['category_name:'] = $array[1];
$newArray['types:'] = $array[3];

Categories