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

Monday, February 14, 2022

[FIXED] Replace non-specified array values with 0

 February 14, 2022     arrays, blacklist, php, replace     No comments   

Issue

I want to replace all array values with 0 except work and home.

Input:

$array = ['work', 'homework', 'home', 'sky', 'door']

My coding attempt:

$a = str_replace("work", "0", $array);

Expected output:

['work', 0, 'home', 0, 0]

Also my input data is coming from a user submission and the amount of array elements may be very large.


Solution

this my final code

//Setup the array of string
$asting = array('work','home','sky','door','march');

/**
Loop over the array of strings with a counter $i,
Continue doing this until it hits the last element in the array
which will be at count($asting)
*/
for($i = 0; $i < count($asting); $i++) {
//Check if the value at the 'ith' element in the array is the one you want to change
//if it is, set the ith element to 0
if ($asting[$i] == 'work') {
   $asting[$i] = 20;
} elseif($asting[$i] == 'home'){
    $asting[$i] = 30;

}else{
    $asting[$i] = 0;
}

echo $asting[$i]."<br><br>";

$total += $asting[$i];
}

echo $total;


Answered By - wyman
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

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